Python: returns function name inside function inside function

I have a decorator that measures the runtime, and I would like to print the name of the function along with the time. This is easy enough as I can just use function.__name__. The hard part is when I attach another decorator, which is in the following format.

def retry_until(desired_return_value, retries=0):
    def decorator(f):
        def wrapper(*args, **kwargs):

In this case, I print f.__name__in the wrapper function, and the value I get for f.__name__is wrapper (). I would like the value to be the name of the function that has been decorated. Is there any way to do this?

Example:

def get_execution_time(f):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        ret = f(*args, **kwargs)
        print(f.__name__ + "() completed in %s seconds" % (time.time() - start_time))
        return ret
    return wrapper

@get_execution_time
def test():    # Function name is "test"
    pass

@get_execution_time
@retry_until(False, 2)
def test():    # Function name is "wrapper", the inner-most function in retry_until
    pass
+4
source share
1 answer

__name__ , functools.wraps :

import functools
def retry_until(desired_return_value, retries=0):
    def decorator(f):
        @functools.wraps(f)
        def wrapper(*args, **kwargs):
            ...
+4

All Articles