Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python function decorator error

I tried to use function decorators, but in this example it dooesn't work for me, can you give me the solution ?

def multiply_by_three(f):
    def decorator():
        return f() * 3
return decorator

@multiply_by_three
def add(a, b):  
    return a + b

print(add(1,2)) # returns (1 + 2) * 3 = 9

Interpreter prints error: "TypeError: decorator() takes 0 positional arguments but 2 were given"

like image 896
siemaeniu500 Avatar asked Jul 08 '26 18:07

siemaeniu500


1 Answers

When you use a decorator, the function you return from the decorator replaces the old function. In other words, the decorator function in multiply_by_three replaces the add function.

This means that each functions signature's should match, including their arguments. However, in your code add takes two arguments while decorator takes none. You need to let decorator receive two arguments as well. You can do this easily by using *args and **kwargs:

def multiply_by_three(f):
    def decorator(*args, **kwargs):
        return f(*args, **kwargs) * 3
    return decorator

If you now decorate your function and run it, you can see it works:

@multiply_by_three
def add(a, b):  
    return a + b

print(add(1,2)) # 9
like image 81
Christian Dean Avatar answered Jul 11 '26 08:07

Christian Dean



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!