Function name of the wrapped function?

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!

+3


source to share


2 answers


Use functools.wraps()

:

Straight from the docs:

Without this factory decorator, the function name example would be "wrapper" and the docstring of the original example () would be 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
>>> 

      

+5


source


Use functools.wraps

or update the wrapped_f attribute __name__

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__)

      

+4


source







All Articles