How can I get the name of the original function?
def wrap(f):
def wrapped_f(*args, **kwargs):
# do something
return wrapped_f
@wrap
def A(params):
# do something
print(A.__name__)
result: wrapped_f, but I need A!
Use functools.wraps()
:
Straight from the docs:
Without the use of this decorator factory, the name of the example function would have been 'wrapper', and the docstring of the original example() would have been lost.
Example:
from functools import wraps
def wrap(f):
@wraps(f)
def wrapped_f(*args, **kwargs):
pass
return wrapped_f
@wrap
def A(params):
pass
print(A.__name__)
Output:
$ python -i foo.py
A
>>>
Use functools.wraps
or update wrapped_f's __name__
attribute manually.
from functools import wraps
def wrap(f):
@wraps(f)
def wrapped_f(*args, **kwargs):
# do something
return wrapped_f
@wrap
def A(params):
# do something
print(A.__name__)