Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python functools wraps() Function



The Pythonwraps() 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 thewraps() function.

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

Parameters

The parameters for thepartial() 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. Thewraps() function ensures the original metadata.

import functoolsdef 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_decoratordef 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 functionGoodbye, JohnAfter calling the functionfarewellFarewells a person

Example 2

Thewraps() 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@mydocdef 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!#$greetReturns greeting text.

Example 3

The wrapper_sum functionwraps 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_sumdef add(x, y):    return x + yprint(add(10, 24))

Output

The output is obtained as follows −

34
python_modules.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp