Preserve metadata when writing a decorator.
What You Will Learn
wraps(original_function) applies update_wrapper to a nested wrapper, retaining name, documentation, annotations, and __wrapped__ for introspection. It does not automatically fix a decorator that mishandles arguments.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
from functools import wraps
def tracked(function):
@wraps(function)
def wrapper(*arguments, **options):
return function(*arguments, **options)
return wrapper
@tracked
def greet(name):
"""Return a greeting."""
return f'Hello {name}'
print(greet.__name__)
print(greet('Ava'))
How the Example Works
- The imports provide the standard-library tools used in the demonstration: functools.
- The definitions tracked, greet separate the main steps into named components; calls to those components drive the example.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
Expected output from the example:
greet
Hello Ava
When You Would Use This
These tools are useful when composing small reusable functions, adapting callbacks, or eliminating repeated work. Pay attention to whether the operation returns a new object, updates state, or produces lazy results. Test a small success case and a boundary case before integrating it into an application.
Practice: Modify the Code
Inspect a decorated function name and docstring with and without wraps().
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Forgetting to forward both *args and **kwargs from wrapper to the original function.
- Overlooking this documented constraint: it does not automatically fix a decorator that mishandles arguments.
Key Takeaways
- Preserve metadata when writing a decorator.
- wraps(original_function) applies update_wrapper to a nested wrapper, retaining name, documentation, annotations, and __wrapped__ for introspection.
- Apply this operation only after checking the assumptions and input conditions shown in the example.