Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Python functools wraps() Function



The Python wraps() function can make debugging and maintain the code more challenging. This function addresses the issue by copying the original function's metadata to the wrapper function.

It prevents the original metadata and other attributes that ensures the decorated functions identity. BY maintaining the original data, it makes the code more readable and easier to understand for the future maintenance.

Syntax

Following is the syntax for the wraps() function.

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

Parameters

The parameters for the partial() function are listed below −

  • wrapped: The function that is wrapped by the decorator.
  • assigned: Tuple specifies which attributes within the function are assigned directly to the wrapper function.
  • updated: A tuple specifies which attributes of he function are directly updated to the wrapper function.

Return Value

This function returns the wrapper function, updated to include the metadata of the original function.

Example 1

In the example below, we define a decorator that prints messages before and after calling function. The wraps() function ensures the original metadata.

import functools
def simple_decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print("Before calling the function")
        x = func(*args, **kwargs)
        print("After calling the function")
        return x
    return wrapper
@simple_decorator
def farewell(name):
    """Farewells a person."""
    print(f"Goodbye, {name}!")
farewell("John")
print(farewell.__name__)
print(farewell.__doc__)

Output

The result is generated as follows −

Before calling the function
Goodbye, John
After calling the function
farewell
Farewells a person

Example 2

The wraps() function preserves the original function's metadata when creating a decorator, and also specifying the decorated function retains the identity of the given data.

In the example below, we directly input data to forward the message using the wraps() function.

def mydoc(func):
    def wrapper(*args, **kwargs):
        return f'{func(*args, **kwargs)}!#$'
    wrapper.__name__ = func.__name__
    wrapper.__doc__ = func.__doc__
    return wrapper
@mydoc
def greet(name):
    """Returns greeting text."""
    return f'Hello, {name}'
print(greet('Alice'))  
print(greet.__name__)  
print(greet.__doc__)	

Output

The code is generated as follows −

Hello, Alice!#$
greet
Returns greeting text.

Example 3

The wrapper_sum function wraps the add function, which calculates the sum of two numbers.

def wrapper_sum(func):
    def wrapper(x, y):
        return func(x, y)
    return wrapper
@wrapper_sum
def add(x, y):
    return x + y
print(add(10, 24))

Output

The output is obtained as follows −

34
python_modules.htm
Advertisements