barciewicz
barciewicz

Reputation: 3773

Is it possible to pass argument to a decorated function?

I have written the below decorator:

import time

def runtime(some_function):   
    def wrapper():
        start = time.time()        
        some_function()         
        runtime = time.time() - start   
        print(runtime)       
    return wrapper              

@runtime
def printing(upper_limit):
    for number in range(upper_limit):
        print(number)

printing(10)
printing(100)
printing(1000)
printing(10000)

Why do I get:

TypeError: wrapper() takes 0 positional arguments but 1 was given

when running the code and how to fix it?

Upvotes: 0

Views: 48

Answers (1)

blhsing
blhsing

Reputation: 106445

You need to make wrapper accept arguments and pass them to some_function. It should also return what some_function returns to be more generic.

def runtime(some_function):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = some_function(*args, **kwargs)
        runtime = time.time() - start
        print(runtime)
        return result
    return wrapper

Upvotes: 2

Related Questions