5

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!

varantir
  • 6,624
  • 6
  • 36
  • 57

2 Answers2

6

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
>>> 
James Mills
  • 18,669
  • 3
  • 49
  • 62
5

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__)
Konstantin
  • 24,271
  • 5
  • 48
  • 65