Search code examples
pythonpython-3.xpython-decorators

Wraps gives TypeError when used in a decorator


I created a decorator to print the name of the function it decorates and it works:

>>> def debug(func):
...    msg=func.__qualname__
...    def wrapper(*args, **kwargs):
...       print(msg)
...       return func(*args, **kwargs)
...    return wrapper
... 
>>> @debug
... def add(x, y):
...    return x+y
... 
>>> add(1,2)
add
3

Now I wanted to apply the wraps decorator to the wrapper but when I did I got the error "TypeError: update_wrapper() got multiple values for argument 'wrapped'"

>>> from functools import wraps
>>>
>>> def debug(func):
...    msg=func.__qualname__
...    @wraps
...    def wrapper(*args, **kwargs):
...       print(msg)
...       return func(*args, **kwargs)
...    return wrapper
... 
>>> @debug
... def add(x, y):
...    return x+y
... 
>>> add(1,2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: update_wrapper() got multiple values for argument 'wrapped'
>>>

What I'm doing wrong and why the error occurs?


Solution

  • Got it. Sorry the issue was I used wraps incorrectly as a decorator. Here is the correct code

    def debug(func):
       msg = func.__qualname__
       @wraps(func)
       def wrapper(*args, **kwargs):
          print(msg)
          return func(*args, **kwargs)
       return wrapper