Open In App

How to preserve Function Metadata while using Decorators?

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. 
Example:






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

Output: 

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

Advantages of using wraps(): 



countdown 0.030733823776245117
wrapper
None
{}
countdown.__wrapped__(100000)




from inspect import signature
 
 
print(signature(countdown))

(n:int)

Article Tags :