@functools.wraps in Python

In Python, the wraps is a decorator of the functools module. It will be used as a convenience function for invoking the update_wrapper as a function decorator when defining a wrapper function. Therefore, it is equivalent to the partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated).

So, this also updates the metadata like __module__, __name__, __doc__ of a wrapper function to look like the wrapped function.

Syntax

The signature for the wraps decorator is as shown below. Here, WRAPPER_ASSIGNMENTS can be __module__, __name__, __doc__ whereas WRAPPER_UPDATES can be __dict__.

@wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)

Python @wraps Examples:

Example 1: In this case, we display the list of the arguments and keywords of the multi-function even before a function call.

from functools import partial,wraps

def show_args(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        print("Calling function ",f.__name__," with the arguments",args,"and  keywords ", kwargs)
        return f(*args, **kwargs)
    return wrapper

#Multiplication function
@show_args
def multi(x,y):
    '''Computing Multiplication of x and y'''
    return x*y
    
#partial functions
mul2 = partial(multi, y=2)
print("2*5= ",mul2(5))

Output

Calling function  multi  with the arguments (5,) and  keywords  {'y': 2}
2*5=  10

Example 2: In this case, we display the list of the arguments and keywords of the power2 function even before a function call.

from functools import partial,wraps
import math
def show_args(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        print("Calling function ",f.__name__," with the arguments",args,"and  keywords ", kwargs)
        return f(*args, **kwargs)
    return wrapper
#partial functions

@show_args
def power2(n,m):
    '''****Computing n raised to m****'''
    return (math.pow(n,m))
 
si = partial(power2,2)
print("Computing 2 raised to 5 result is ",si(5))

Output

Calling function  power2  with the arguments (2, 5) and  keywords  {}
Computing 2 raised to 5 result is  32.0

Example 3: In this case, we are displaying the list of the arguments and keywords of the simple int function even before a function call.

from functools import partial,wraps

def show_args(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        print("Calling function ",f.__name__," with the arguments",args,"and  keywords ", kwargs)
        return f(*args, **kwargs)
    return wrapper
#partial functions

@show_args
def simpleint(p,r,t):
    '''****Computing Simple Interest****'''
    return (p*r*t)/100.0
 
si = partial(simpleint,7,t=3)
print("Simple interest is ",si(10000))

Output

Calling function  simpleint  with the arguments (7, 10000) and  keywords  {'t': 3}
Simple interest is  2100.0

Conclusion

Hence, We can use the wraps decorator as a convenience function to help the update_wrapper.

References

Happy Learning 🙂