Sub topic 6
update_wrapper and the __wrapped__ attribute
This chapter assumes you can write a basic decorator with the @ syntax and that you have seen functools.wraps used on an inner wrapper function. Here you will look at what wraps does internally and at the __wrapped__ attribute it leaves behind.
wraps is a thin layer over update_wrapper
functools.wraps is not a separate mechanism. It is a convenient way to call functools.update_wrapper, which does the actual copying. These two decorators behave the same way:
import functools
def deco_a(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
def deco_b(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return functools.update_wrapper(wrapper, func)
@deco_a
def one():
"""First."""
@deco_b
def two():
"""Second."""
print(one.__name__, one.__doc__) # one First.
print(two.__name__, two.__doc__) # two Second.update_wrapper(wrapper, wrapped) modifies wrapper in place and returns it. That is why the return line in deco_b works. wraps(func) simply returns a decorator that will call update_wrapper on whatever function it receives.
What gets copied
update_wrapper does three things:
- It copies the attributes listed in
functools.WRAPPER_ASSIGNMENTSfrom the original to the wrapper. These include__module__,__name__,__qualname__,__doc__and__annotations__. Recent Python versions add more, so check the documentation for your version. - It merges the attributes listed in
functools.WRAPPER_UPDATESinto the wrapper. By default this is the__dict__, so any custom attributes set on the original function appear on the wrapper too. - It sets
wrapper.__wrapped__to the original function.
If the original lacks one of the assigned attributes, that attribute is skipped without an error.
The __wrapped__ attribute
The __wrapped__ attribute is a direct reference to the function that was decorated. It gives you two useful abilities.
First, you can call the undecorated function and skip the decorator's behavior, for example in a test:
import functools
import inspect
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 add(a, b=1):
"""Add two numbers."""
return a + b
print(add(2, 3)) # prints "calling add", then 5
print(add.__wrapped__(2, 3)) # 5, with no logging
print(inspect.signature(add)) # (a, b=1)Second, tools such as inspect.signature follow __wrapped__. The real wrapper has the signature (*args, **kwargs), but inspect.signature(add) reports (a, b=1), the signature of the original. Help systems, IDEs and documentation generators rely on this. Without __wrapped__, the signature would show only (*args, **kwargs).
Following a chain with inspect.unwrap
When decorators are stacked, each layer points to the one below it through __wrapped__. inspect.unwrap follows the whole chain and returns the innermost function.
import functools
import inspect
from functools import cache
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@log_calls
@cache
def double(n):
return n * 2
print(double.__wrapped__ is not None) # True
print(hasattr(double.__wrapped__, "cache_info")) # True
print(inspect.unwrap(double).__name__) # double
print(hasattr(inspect.unwrap(double), "cache_info")) # FalseThe cache decorator itself uses update_wrapper. Its result keeps the original name and has its own __wrapped__. So one unwrap call goes through both layers and reaches the plain function.
Customizing what is copied
update_wrapper accepts two optional arguments, assigned and updated. They replace the default attribute lists. This is rarely needed, but it helps when you want a wrapper to keep its own docstring:
import functools
def original(x):
"""Original docs."""
return x
def wrapper(x):
"""Wrapper docs."""
return original(x)
functools.update_wrapper(wrapper, original, assigned=("__name__",), updated=())
print(wrapper.__name__) # original
print(wrapper.__doc__) # Wrapper docs.Only __name__ was copied, and __dict__ was left alone. The __wrapped__ attribute is still set.
Gotchas
- Decorators written with
wrapsonly expose__wrapped__if you actually usewrapsorupdate_wrapper. A naive decorator leaves no link back. __wrapped__is the way to reach the original function. It does not change how the decorator behaves when called.- Because
__dict__is merged, attributes set on the wrapper later are not pushed back to the original function.
Exercise
A decorator uses functools.update_wrapper(wrapper, func). How can you call the original, undecorated func from outside the decorator, and what does inspect.signature report for the decorated function?
Show answer
Call wrapper._wrapped(...), or use inspect.unwrap(wrapper) for stacked decorators. inspect.signature follows wrapped_, so it reports the original function's signature instead of (args, *kwargs).