Talk about lifting the role of decorator of python3 added
- 2020-12-19 21:06:42
- OfStack
A decorator is already acting on a function and you want to undo it, accessing the original unwrapped function directly.
Assuming the decorator is implemented via @wraps, you can access the original function by accessing the wrapped property:
>>> @somedecorator
>>> def add(x, y):
... return x + y
...
>>> orig_add = add.__wrapped__
>>> orig_add(3, 4)
7
>>>
If there are multiple wrappers:
In [588]: from functools import wraps
In [589]: def decorator1(func):
...: @wraps(func)
...: def wrapper(*args, **kwargs):
...: print ('Decorator 1')
...: return func(*args, **kwargs)
...: return wrapper
...:
In [590]: def decorator2(func):
...: @wraps(func)
...: def wrapper(*args, **kwargs):
...: print ('Decorator 2')
...: return func(*args, **kwargs)
...: return wrapper
...:
In [591]: @decorator1
...: @decorator2
...: def add(x, y):
...: return x+y
...:
In [592]: add(2,3)
Decorator 1
Decorator 2
Out[592]: 5
In [593]: add.__wrapped__(2, 3)
Decorator 2
Out[593]: 5
In [594]: add.__wrapped__.__wrapped__(2,3)
Out[594]: 5
Python Cookbook