Middle
What is the purpose of the wraps decorator in Python?
sobes.tech AI
Answer from AI
The wraps decorator from the functools module is used to preserve the metadata of the wrapped function (such as name, docstring, annotations, and module) when creating a wrapper function.
Without wraps, the wrapped function will have the metadata of the wrapper function, which can make debugging, introspection, and tool usage (e.g., Sphinx for documentation) more difficult.
from functools import wraps
def my_decorator(func):
# Preserves the original function’s metadata
@wraps(func)
def wrapper(*args, **kwargs):
print("Before function call")
result = func(*args, **kwargs)
print("After function call")
return result
return wrapper
@my_decorator
def greeted_function(name):
"""This is the docstring of the greeted function."""
print(f"Hello, {name}!")
# Without wraps, greeted_function.__name__ would be 'wrapper',
# greeted_function.__doc__ would be None, etc.
print(f"Function name: {greeted_function.__name__}")
print(f"Function docstring: {greeted_function.__doc__}")
greeted_function("World")
Comparison table:
| Attribute | Without functools.wraps |
With functools.wraps |
|---|---|---|
__name__ |
Name of the wrapper function | Original function's name |
__doc__ |
Docstring of the wrapper function | Original function's docstring |
__module__ |
Module of the wrapper function | Original function's module |
__annotations__ |
Annotations of the wrapper function | Annotations of the original function |
__wrapped__ |
Not present | Reference to the original function |