Sub topic 6
Keeping name and docstring with functools.wraps
This chapter assumes you can write a basic decorator with a nested wrapper function, use the @ syntax, and forward arguments with *args and **kwargs. You do not need to know about stacking or decorator factories yet. Those come later, and they depend on what you learn here.
The problem: the wrapper replaces the original
When you decorate a function, the name in your module now points to the wrapper, not to the function you wrote. The wrapper is a different function object with its own __name__, __doc__, and other attributes. Anything that reads those attributes sees the wrapper's values.
def timer(func):
def wrapper(*args, **kwargs):
"""Wrapper docstring."""
return func(*args, **kwargs)
return wrapper
@timer
def slow_add(a, b):
"""Add two numbers."""
return a + b
print(slow_add.__name__) # wrapper
print(slow_add.__doc__) # Wrapper docstring.
print(slow_add) # <function timer.<locals>.wrapper at 0x...>The decorator worked, since slow_add(2, 3) still returns 5. But the function has lost its identity. This causes real problems:
- Debugging: tracebacks, logs, and
repr()output showwrapperfor every decorated function. You cannot tell which one failed. - Documentation:
help(slow_add)and documentation generators show the wrapper's docstring, or none at all. - Introspection: tools such as
inspect.signature, test runners, web frameworks, and command-line libraries read names and docstrings to register routes, build help text, or label tests. - Pickling: pickle stores functions by their qualified name. A wrapper that reports the wrong name can break this.
The manual fix
You could copy the attributes yourself.
def timer(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
wrapper.__name__ = func.__name__
wrapper.__doc__ = func.__doc__
return wrapperThis works for two attributes, but a function carries more than that: __module__, __qualname__, __dict__, and __annotations__. Copying them by hand in every decorator is repetitive and easy to get wrong. The standard library provides a helper for it.
Using functools.wraps
functools.wraps is a decorator that you apply to the wrapper. You give it the original function, and it copies the metadata from the original onto the wrapper.
import functools
import time
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
try:
return func(*args, **kwargs)
finally:
elapsed = time.perf_counter() - start
print(f"{func.__name__} took {elapsed:.4f}s")
return wrapper
@timer
def slow_add(a, b):
"""Add two numbers after a short pause."""
time.sleep(0.1)
return a + b
print(slow_add(2, 3))
print(slow_add.__name__) # slow_add
print(slow_add.__doc__) # Add two numbers after a short pause.The line @functools.wraps(func) sits directly above def wrapper. It is the only change from the broken version, and it fixes the name, the docstring, and the other attributes.
Notice that this is itself a decorator that takes an argument. functools.wraps(func) is called first and returns a decorator, which then receives wrapper. You will build your own decorators with this shape in the chapter on decorator factories.
What wraps actually copies
functools.wraps is a shortcut for functools.update_wrapper. It calls update_wrapper(wrapper, func) and returns the wrapper. The function does three things.
| Step | Attributes | What happens |
|---|---|---|
| Assigned | `__module__`, `__name__`, `__qualname__`, `__doc__`, `__annotations__` (plus `__type_params__` in Python 3.12 and later) | Each value is copied from the original onto the wrapper, replacing the wrapper's own value. |
| Updated | `__dict__` | The original's attribute dictionary is merged into the wrapper's. |
| Linked | `__wrapped__` | The wrapper gets a new attribute that points to the original function. |
The tuples that control this are functools.WRAPPER_ASSIGNMENTS and functools.WRAPPER_UPDATES. You can pass your own assigned and updated arguments to wraps if you need to copy fewer or more attributes. Most code never does.
import functools
print(functools.WRAPPER_ASSIGNMENTS)
print(functools.WRAPPER_UPDATES)The __wrapped__ attribute
After wraps runs, wrapper.__wrapped__ is the original function. This gives you a way to reach through the decorator.
import functools
def log(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print("calling", func.__name__)
return func(*args, **kwargs)
return wrapper
@log
def add(a, b):
return a + b
print(add(1, 2)) # prints "calling add", then 3
print(add.__wrapped__(1, 2)) # 3, with no loggingThis is useful in tests, where you may want to call the plain function without the decorator's side effects. It also lets inspect.signature report the original parameters instead of (*args, **kwargs).
import functools
import inspect
def passthrough(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@passthrough
def connect(host, port=5432):
pass
print(inspect.signature(connect)) # (host, port=5432)Without wraps, the same call would print (*args, **kwargs). The inspect module follows the __wrapped__ chain to find the real signature. This is why help systems and frameworks that inspect parameters behave better with decorated functions when you use wraps.
What wraps does not do
functools.wraps copies descriptive attributes. It does not change how the wrapper behaves.
- The real signature is still `(*args, kwargs)
.** Python'sinspect.signaturereports the original signature through_wrapped_`, but the wrapper itself accepts anything. Calling a decorated function with the wrong arguments fails inside the wrapped call, not at the wrapper. The traceback then includes the wrapper frame. - Attributes on the wrapper are overwritten. Because
__dict__is merged, a key the original function has will replace the same key on the wrapper. If the wrapper stores its own state under the same name, you lose it. - It does not help classes with
__call__. A class-based decorator needsfunctools.update_wrapper(self, func)in__init__, because there is no inner function to put@wrapson. A later chapter covers this. - It does not fix type hints. Static type checkers see the wrapper's declared type, not the original's. The chapter on
ParamSpeccovers that.
A shared dictionary gotcha
Since update_wrapper merges __dict__, any attribute set on the original function before decoration is carried over to the wrapper.
import functools
def mark(func):
func.is_marked = True
return func
def passthrough(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@passthrough
@mark
def job():
pass
print(job.is_marked) # TrueHere mark runs first and sets is_marked on job. Then passthrough wraps it, and wraps copies that attribute onto the wrapper. If you reverse the order, mark sets the attribute on the wrapper, which also works. But a decorator that stores state on the function object after the fact can see that state split between the wrapper and the original if the order changes. When you need shared state, keep it in a closure variable or on the wrapper itself, and choose one place on purpose.
Seeing the difference in a traceback
The most common day-to-day payoff is readable error output. Here a decorated function raises an error, and a logging decorator reports the name.
import functools
def report_errors(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as exc:
print(f"{func.__qualname__} failed: {exc}")
raise
return wrapper
class Account:
@report_errors
def withdraw(self, amount):
raise ValueError("insufficient funds")
try:
Account().withdraw(50)
except ValueError:
passThe output is Account.withdraw failed: insufficient funds. The __qualname__ attribute includes the class name, and it is one of the values that wraps copies. Without wraps, the message would name report_errors.<locals>.wrapper.
When to apply wraps
Use functools.wraps in every decorator that returns a wrapper function. There is almost no cost, and the benefits show up in debugging, documentation, and tooling. Place it on the innermost function that you return, directly above the def.
A short checklist for each decorator you write:
- Import
functools. - Add
@functools.wraps(func)above the innerdef wrapper. - Forward
*argsand**kwargs, and return the wrapped call's result. - Test by printing
__name__and__doc__on a decorated function.
Test the last step in your own code. A quick assertion catches a forgotten wraps before it causes confusing logs later.
import functools
def good(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@good
def sample():
"""Sample docstring."""
assert sample.__name__ == "sample"
assert sample.__doc__ == "Sample docstring."
assert sample.__wrapped__.__name__ == "sample"
print("metadata preserved")Exercise
A decorator returns wrapper without using functools.wraps. A function load_config with the docstring "Read settings." is decorated with it. What do load_config.__name__ and load_config.__doc__ report, which attribute added by wraps would let you call the undecorated function, and how do you get it?
Show answer
Without wraps, __name__ is "wrapper" and __doc__ is the wrapper's own docstring, or None if it has none. Adding @functools.wraps(func) above the wrapper makes them report "loadconfig" and "Read settings." It also sets `wrapped on the wrapper, so loadconfig._wrapped_()` calls the original function without the decorator's behavior.
Exercise
Why does inspect.signature show (*args, **kwargs) for a decorated function when wraps is missing, but show the original parameters when wraps is present?
Show answer
inspect.signature follows the __wrapped__ attribute to find the original function and reads its parameters. Only functools.wraps (or update_wrapper) sets __wrapped__. Without it, inspect sees only the wrapper, whose real parameters are *args and **kwargs.