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!
__wrapped__ in Python decorators As we can see from the code of the functools module 1, when decorating an object, there is an attribute named __wrapped__ that holds the reference to the original one. So now if we use this, we can access it directly without having to resort to the old quirks.
A wrapper function is a subroutine (another word for a function) in a software library or a computer program whose main purpose is to call a second subroutine or a system call with little or no additional computation.
wraps() is a decorator that is applied to the wrapper function of a decorator. It updates the wrapper function to look like wrapped function by copying attributes such as __name__, __doc__ (the docstring), etc. Parameters: wrapped: The function name that is to be decorated by wrapper function.
Functools module is for higher-order functions that work on other functions. It provides functions for working with other functions and callable objects to use or extend them without completely rewriting them. This module has two classes – partial and partialmethod.
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__)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With