Skip to content
Related Articles
Open in App
Not now

Related Articles

How to preserve Function Metadata while using Decorators?

Improve Article
Save Article
Like Article
  • Difficulty Level : Hard
  • Last Updated : 04 Aug, 2022
Improve Article
Save Article
Like Article

Decorators are a very powerful and useful tool in Python since it allows programmers to modify the behavior of function or class. Decorators allow us to wrap another function in order to extend the behavior of the wrapped function, without permanently modifying it.
Note: For more information, refer Decorators in Python

How to preserve Metadata?

This can be done using the wraps() method of the functools. It updates the wrapper function to look like wrapped function by copying attributes such as __name__, __doc__ (the docstring), etc. 


import time
from functools import wraps
def timethis(func):
    '''Decorator that reports the execution time.'''
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(func.__name__, end-start)
        return result
    return wrapper
def countdown(n:int):
    '''Counts down'''
    while n > 0:
        n -= 1


countdown 0.00827932357788086
Counts down
{'n': <class 'int'>}

Advantages of using wraps(): 

  • Copying decorator metadata is an important part of writing decorators. If you forget to use @wraps, you’ll find that the decorated function loses all sorts of useful information. For example, if omitted, the output of the last example would look like this:
countdown 0.030733823776245117
  • An important feature of the @wraps decorator is that it makes the wrapped function available to you in the __wrapped__ attribute. For example, if you want to access the wrapped function directly, you could do this:
  • The presence of the __wrapped__ attribute also makes decorated functions properly expose the underlying signature of the wrapped function. For example: 


from inspect import signature

  • Output:

My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!