4

I've got a decorator that measures execution time, and I'd like to print the function name along with the time. That's easy enough typically, as I can just use function.__name__. The tricky 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'd like the value to be the function name that is decorated. Is there a 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

1 Answer 1

4

You could reassign __name__ manually, or you could just use functools.wraps to do that and a couple related things for you:

import functools
def retry_until(desired_return_value, retries=0):
    def decorator(f):
        @functools.wraps(f)
        def wrapper(*args, **kwargs):
            ...
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks heaps for that. The wraps(f) decorator worked perfectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.