Get the name of a decorated function? [duplicate] Get the name of a decorated function? [duplicate] django django

Get the name of a decorated function? [duplicate]


functools.wraps is not needed! Just use func.__name__

import timedef timeit(func):    def timed(*args, **kwargs):        ts = time.time()        result = func(*args, **kwargs)        te = time.time()        print('Function', func.__name__, 'time:', round((te -ts)*1000,1), 'ms')        print()        return result    return timed@timeitdef math_harder():    [x**(x%17)^x%17 for x in range(1,5555)]math_harder()@timeitdef sleeper_agent():    time.sleep(1)sleeper_agent()

Outputs:

Function math_harder time: 8.4 msFunction sleeper_agent time: 1003.7 ms


You may want to use wraps from functools. See the example

>>> from functools import wraps>>> def my_decorator(f):...     @wraps(f)...     def wrapper(*args, **kwargs):...         print('Calling decorated function')...         return f(*args, **kwargs)...     return wrapper...>>> @my_decorator... def example():...     """Docstring"""...     print('Called example function')...>>> example()Calling decorated functionCalled example function>>> example.__name__'example'>>> example.__doc__'Docstring'


In addition to functools.wraps, you can check out the decorator module which was designed to help with this problem.