简体   繁体   中英

How to get the original name of a function after it is wrapped by function decorator?

The Code

def blahblah(func):
    def wrapper(*args):
        pass # blah blah blah....
    return wrapper

@blahblah
def func1(arg1):
    pass # blah blah blah

@blahblah
def func2(arg1):
    pass # blah blah blah

functions = [func1, func2]

for func in functions:
    print(func.__name__, func(0))

What I want is to get the original name of this code, like "func1" and "func2". But the code written before just gives me "wrapper" and "wrapper". Is there any way around? 'd better without changing the wrapping code.

The Output

  wrapper None
  wrapper None

Ideal Output

  func1 None
  func2 None

You can use the functools.wraps helper function as follows which'll preserve the original name and doc string of the wrapped function, eg:

from functools import wraps

def blahblah(func):
    @wraps(func)
    def wrapper(*args):
        pass # blah blah blah....
    return wrapper

@blahblah
def func1(arg1):
    pass # blah blah blah

print(func1.__name__)
# func1

As kojiro points out in comments, while this preserves the name and doc strings, there are things to be aware of - https://hynek.me/articles/decorators/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM