68. Function Wrapping with wraps
1. Basic Usage of functools.wraps
Preserve function metadata like name and docstring when wrapping a function with a decorator.
Copy
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.
Copy
3. Function Signature Preservation
functools.wraps helps preserve the function's signature even after being wrapped by a decorator.
Copy
4. Handling Arguments with functools.wraps
Use functools.wraps to ensure the function arguments are handled properly when wrapped.
Copy
Output:
Copy
5. Preserving Function's Docstring
Preserve the docstring of the wrapped function using functools.wraps.
Copy
6. Preserving Function's Original Return Value
Ensure that the function’s original return value is returned properly after being wrapped.
Copy
Output:
Copy
7. Example with Arguments and Keyword Arguments
Ensure that both arguments and keyword arguments are passed correctly.
Copy
Output:
Copy
8. Debugging with functools.wraps
Use functools.wraps to retain function metadata for debugging purposes.
Copy
Output:
Copy
9. Preserving Function Attributes
You can preserve custom attributes of the wrapped function using functools.wraps.
Copy
10. Dynamic Function Wrapping with functools.wraps
Dynamically wrap functions and preserve their metadata.
Copy
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