Sub topic 5
Fixing it with wraps
This chapter assumes you can write a basic decorator with the @ syntax and that you know a function is an object with attributes such as __name__. The previous chapter showed that a naive decorator replaces a function with its inner wrapper, and that the wrapper's name and docstring replace the original's. Here you fix that with functools.wraps, and you learn what it copies, what it leaves alone, and how it goes wrong.
The one-line fix
functools.wraps is a decorator factory. You give it the function being wrapped, and it returns a decorator that copies identifying metadata from that function onto the wrapper. You apply it to the inner function:
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(name):
"""Return a greeting."""
return f"Hello, {name}"
print(greet("Ada"))
print(greet.__name__)
print(greet.__doc__)
print(greet.__wrapped__ is not None)Running it prints:
calling greet
Hello, Ada
greet
Return a greeting.
TrueWithout the @functools.wraps(func) line, greet.__name__ would be wrapper and greet.__doc__ would be None. The call behavior is the same either way. What changes is everything that reads the metadata: help(), debuggers, tracebacks, logging, documentation generators, and frameworks that register functions by name.
What wraps copies
wraps is a thin layer over functools.update_wrapper, which does the actual copying. It does two kinds of copying, controlled by two module constants.
| Constant | Behavior | Attributes |
|---|---|---|
| `WRAPPER_ASSIGNMENTS` | Assigned directly from the original to the wrapper | `__module__`, `__name__`, `__qualname__`, `__doc__`, `__annotations__`, and `__type_params__` (Python 3.12+) |
| `WRAPPER_UPDATES` | Merged into the wrapper's existing attributes | `__dict__` |
It also sets one extra attribute: wrapper.__wrapped__ = func. This is a reference to the original function, and it is not in either constant.
You can check the exact tuples on your interpreter:
import functools
print(functools.WRAPPER_ASSIGNMENTS)
print(functools.WRAPPER_UPDATES)The output varies by Python version. Python 3.12 added __type_params__ to the first tuple.
The diagram shows what happens at decoration time.
Why the annotations and the signature matter
Your wrapper is declared as wrapper(*args, **kwargs), so its real signature says nothing about the original parameters. wraps does not rewrite the signature. Instead, inspect.signature follows the __wrapped__ attribute and reports the original function's signature:
import functools
import inspect
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
def greet(name: str, punctuation: str = "!") -> str:
return f"Hello, {name}{punctuation}"
decorated = log_calls(greet)
print(inspect.signature(decorated))
print(decorated.__wrapped__ is greet)
print(inspect.unwrap(decorated) is greet)The output is:
(name: str, punctuation: str = '!') -> str
True
Trueinspect.unwrap follows the __wrapped__ chain all the way down, which is useful when several decorators are stacked. Tools such as help(), IDE hints, and test frameworks that inject arguments by parameter name all rely on this behavior.
Note that the wrapper still accepts anything. Calling decorated(1, 2, 3, 4) fails inside the original function with a TypeError, not at the wrapper's own signature. wraps changes what tools see, not what the wrapper enforces.
Function attributes are merged
Because wraps updates the wrapper's __dict__, any custom attributes set on the original function carry over. This matters when one decorator marks a function and another decorator wraps it afterward:
import functools
def mark_public(func):
func.is_public = True
return func
def passthrough(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@passthrough
@mark_public
def handler():
return "handled"
print(handler.is_public) # TrueIf passthrough omitted wraps, handler.is_public would raise AttributeError, and a registry that scans for the marker would silently skip the function.
The merge is a plain dict.update. It copies references, not deep copies, so a mutable value stored as a function attribute is shared between the original and the wrapper. It is also one-directional and happens once, at decoration time. If you set a new attribute on the original function afterward, the wrapper does not see it.
Decorators that take arguments
When a decorator accepts its own arguments, there are three nested functions. wraps still goes on the innermost one, and it still takes the function being decorated, not the decorator's arguments:
import functools
def retry(times):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
last_error = None
for attempt in range(1, times + 1):
try:
return func(*args, **kwargs)
except ValueError as error:
last_error = error
print(f"attempt {attempt} failed: {error}")
raise last_error
return wrapper
return decorator
calls = {"n": 0}
@retry(times=3)
def flaky():
"""Succeed on the third call."""
calls["n"] += 1
if calls["n"] < 3:
raise ValueError(f"call {calls['n']}")
return "ok"
print(flaky())
print(flaky.__name__, "-", flaky.__doc__)The output is:
attempt 1 failed: call 1
attempt 2 failed: call 2
ok
flaky - Succeed on the third call.A useful check is to ask which function each layer receives. retry receives times, decorator receives func, and wrapper receives the call's arguments. wraps(func) belongs where func is in scope and where the wrapper is defined, which is inside decorator.
Common errors
Forgetting to call wraps with the function
wraps needs an argument. Writing the bare form is a mistake that Python does not flag at definition time:
import functools
def broken(func):
@functools.wraps # wrong: missing (func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@broken
def add(a, b):
return a + b
# add(1, 2) raises TypeError, because wraps received wrapper as its
# "wrapped" argument and returned a decorator, so add is no longer a function.
print(type(add))Here functools.wraps(wrapper) returns a decorator function, and that returned decorator replaces wrapper. The name add ends up bound to the decorator that wraps returned. Calling add(1, 2) then passes 1 where the decorator expects a function and fails with a confusing error. The fix is @functools.wraps(func).
Applying wraps to the wrong function
wraps(func) must decorate the wrapper, never the original. Reversing them overwrites the original's metadata with the wrapper's, which is the opposite of what you want.
Dropping the return value
wraps fixes metadata only. A wrapper that calls func(*args, **kwargs) without return makes every decorated function return None. This bug survives code review because the metadata looks perfect.
Expecting wraps to change behavior
wraps does not preserve default arguments in the wrapper, does not validate calls, and does not make a coroutine function look like a coroutine function to asyncio.iscoroutinefunction. If you wrap an async def function with a plain def wrapper that returns the coroutine, the wrapper works when awaited, but checks that inspect the wrapper itself see an ordinary function. Write an async def wrapper when the decorated function is asynchronous.
Practical effects you can observe
Three places where wraps changes visible behavior:
- Tracebacks and logs. Frames show the wrapper's code location either way, but any log line using
func.__name__or__qualname__reports the real function only whenwrapsis applied. Logging libraries also commonly use__module__. - Registries and web frameworks. Frameworks that map function names to routes or commands can collide when every decorated function is named
wrapper. Two routes with the same endpoint name raise an error in some frameworks. - Pickling by reference.
picklestores a function as its module plus qualified name. A decorated function withoutwrapshas the qualified namelog_calls.<locals>.wrapper, which cannot be looked up, so pickling fails. Withwraps, the wrapper carries the original's__module__and__qualname__, and the lookup finds the decorated object at module level.
When to reach for update_wrapper instead
wraps(func) is shorthand for functools.partial(update_wrapper, wrapped=func, ...). It is the right tool for nested functions. For cases where you already have both objects, such as a callable class instance, call update_wrapper directly. The next chapter covers that form and the __wrapped__ attribute in more detail.
You can also narrow what is copied through the assigned and updated parameters:
import functools
def quiet(func):
@functools.wraps(func, assigned=("__name__", "__doc__"), updated=())
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@quiet
def ping():
"""Return pong."""
return "pong"
print(ping.__name__, ping.__doc__)
print(ping.__qualname__)The first print shows ping Return pong.. The second shows quiet.<locals>.wrapper, because __qualname__ was left out of assigned. Narrowing is rarely useful. Its most common purpose is to skip an attribute the original object does not have, since update_wrapper silently ignores missing attributes.
Checklist for writing a decorator
- Put
@functools.wraps(func)directly above the innerdef wrapper. - Accept
*args, **kwargsand pass them through unchanged. - Return the original function's result.
- For decorators with arguments, keep
wraps(func)on the innermost function. - Check
name.__name__andhelp(name)once while testing.
Exercise
A teammate writes @functools.wraps (no parentheses, no argument) above the inner wrapper function of a decorator. Calling any decorated function now fails. What does functools.wraps return in that case, and how do you fix the decorator?
Show answer
functools.wraps(wrapper) is evaluated with the inner function passed as the wrapped argument, so it returns a decorator (a partial of update_wrapper), not a function. That returned decorator becomes the decorated function's replacement. Calling it with the normal arguments fails because it expects a function to wrap. The fix is @functools.wraps(func), where func is the function the outer decorator received.
Exercise
A decorator uses @functools.wraps(func) correctly. The original function is def total(a: int, b: int = 0) -> int. What does inspect.signature report for the decorated function, and why? What does decorated(1, 2, 3) do?
Show answer
It reports (a: int, b: int = 0) -> int, because wraps sets __wrapped__ to the original and inspect.signature follows __wrapped__. Calling decorated(1, 2, 3) still runs the wrapper, which forwards all three arguments to the original, so it raises a TypeError for too many positional arguments. wraps changes what tools see, not what the wrapper accepts.