How does @functools.wraps preserve metadata when writing decorators?
Short answer
When a decorator replaces a function with a wrapper, the wrapper loses the original's __name__, __doc__, and other metadata.
Advertisement
AModel answer
When a decorator replaces a function with a wrapper, the wrapper loses the original's __name__, __doc__, and other metadata. @functools.wraps(func) applied to the wrapper copies that metadata over, so introspection tools, help(), and debuggers still show the original function's identity.
import functools
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f'Calling {func.__name__}')
return func(*args, **kwargs)
return wrapper
@log_calls
def greet():
'''Say hello.'''
pass
print(greet.__name__, greet.__doc__)Real-world example
A web framework's logging decorator uses wraps so Flask's URL routing still sees the correct endpoint function name instead of 'wrapper'.
Likely follow-ups
- What breaks if you omit functools.wraps?
- What is functools.WRAPPER_ASSIGNMENTS?
Related topics