Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 958
amadain Avatar asked Jun 01 '17 07:06

amadain


1 Answers

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
like image 168
amadain Avatar answered Oct 31 '22 16:10

amadain