68. Function Wrapping with wraps

Here are 10 Python code snippets demonstrating the use of functools.wraps to preserve metadata when creating decorators:


1. Basic Usage of functools.wraps

Preserve function metadata like name and docstring when wrapping a function with a decorator.

import functools

def simple_decorator(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

@simple_decorator
def example_function():
    """This is a decorated function."""
    return "Hello"

print(example_function.__name__)  # Output: example_function
print(example_function.__doc__)   # Output: This is a decorated function.

2. Preserving Metadata with Multiple Decorators

When using multiple decorators, functools.wraps ensures that the function’s metadata is retained.


3. Function Signature Preservation

functools.wraps helps preserve the function's signature even after being wrapped by a decorator.


4. Handling Arguments with functools.wraps

Use functools.wraps to ensure the function arguments are handled properly when wrapped.

Output:


5. Preserving Function's Docstring

Preserve the docstring of the wrapped function using functools.wraps.


6. Preserving Function's Original Return Value

Ensure that the function’s original return value is returned properly after being wrapped.

Output:


7. Example with Arguments and Keyword Arguments

Ensure that both arguments and keyword arguments are passed correctly.

Output:


8. Debugging with functools.wraps

Use functools.wraps to retain function metadata for debugging purposes.

Output:


9. Preserving Function Attributes

You can preserve custom attributes of the wrapped function using functools.wraps.


10. Dynamic Function Wrapping with functools.wraps

Dynamically wrap functions and preserve their metadata.


These examples demonstrate how functools.wraps is used to ensure that the decorated function retains its original metadata such as name, docstring, and signature. This is especially important when writing decorators, as it allows for better introspection, debugging, and clarity in the code.

Last updated