Sub topic 6
update_wrapper and the __wrapped__ attribute
This chapter assumes you can write a decorator with an inner wrapper(*args, **kwargs) function, and that you have seen @functools.wraps(func) used on that inner function. The previous chapter showed what wraps fixes. This one opens it up. You will see that wraps is a thin layer over functools.update_wrapper, what that function copies, and why it also sets a __wrapped__ attribute. You will also see how tools like inspect use __wrapped__, and where the behavior surprises people.
wraps is update_wrapper in disguise
functools.update_wrapper(wrapper, wrapped) copies metadata from wrapped onto wrapper and returns wrapper. You can call it directly instead of using the decorator form:
import functools
def log_calls(func):
def wrapper(*args, **kwargs):
print(f"calling {func.__name__}")
return func(*args, **kwargs)
return functools.update_wrapper(wrapper, func)
@log_calls
def greet(name):
"""Return a greeting."""
return f"Hello, {name}"
print(greet("Ada"))
print(greet.__name__) # greet
print(greet.__doc__) # Return a greeting.
print(greet.__wrapped__ is not None) # Truefunctools.wraps(func) does the same job. It returns a ready-made decorator, so this:
@functools.wraps(func)
def wrapper(*args, **kwargs):
...is equivalent to defining wrapper and then calling functools.update_wrapper(wrapper, func) on it. Internally, wraps(func) is partial(update_wrapper, wrapped=func, ...). That is the same partial tool from the start of this tutorial, applied to update_wrapper.
The two forms differ in convenience, not behavior. The decorator form keeps the metadata declaration next to the def. The function form is useful when the wrapper is not a plain function, as shown below.
What update_wrapper copies
update_wrapper does three things, in this order:
- It assigns a fixed list of attributes from
wrappedtowrapper. - It merges selected dictionaries from
wrappedinto the matching ones onwrapper. - It sets
wrapper.__wrapped__ = wrapped.
The first two lists are exposed as module constants:
| Constant | Meaning | Typical contents |
|---|---|---|
| `functools.WRAPPER_ASSIGNMENTS` | Attributes copied by assignment | `__module__`, `__name__`, `__qualname__`, `__doc__`, plus annotation-related names |
| `functools.WRAPPER_UPDATES` | Attributes merged with `dict.update` | `__dict__` |
The exact contents of WRAPPER_ASSIGNMENTS vary between Python versions. For example, 3.12 added __type_params__. Print the constants on your interpreter instead of memorizing them:
import functools
print(functools.WRAPPER_ASSIGNMENTS)
print(functools.WRAPPER_UPDATES) # ('__dict__',)Two details follow from this design.
- Missing attributes are skipped. If
wrappedhas no__name__,update_wrapperleaves that attribute alone instead of raisingAttributeError. This matters because many callables are not functions. __dict__is merged, not replaced. Any custom attributes on the original function, such asfunc.tag = "a", are copied into the wrapper's own__dict__. Attributes already on the wrapper stay unless the original overwrites them.
Customizing assigned and updated
update_wrapper takes two optional keyword arguments, assigned and updated. They replace the default lists. wraps accepts the same keywords.
import functools
def original():
"""Original doc."""
original.tag = "a"
def w1():
pass
functools.update_wrapper(w1, original)
print(w1.__name__, w1.tag, w1.__wrapped__ is original)
# original a True
def w2():
pass
functools.update_wrapper(w2, original, assigned=("__doc__",), updated=())
print(w2.__name__, w2.__doc__, hasattr(w2, "tag"), w2.__wrapped__ is original)
# w2 Original doc. False TrueIn the second call, only __doc__ is assigned and no dictionaries are merged. The wrapper keeps its own name, receives no tag attribute, and still gets __wrapped__. The __wrapped__ link is always set, whatever you pass for the two lists.
You will rarely need this. A reasonable use is a decorator that deliberately renames the function, such as one that registers a handler under a new name. Dropping __name__ from assigned keeps the wrapper's own name.
The __wrapped__ attribute
__wrapped__ is a plain reference from the wrapper to the function it wraps. It has three uses.
Reaching the original. greet.__wrapped__ is the undecorated function. In tests, you can call it directly to skip the decorator's behavior, such as logging, retries, or authorization checks.
Following a chain. When several decorators are stacked and each uses wraps, every layer points at the next one:
import functools
import inspect
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"calling {func.__name__}{args}")
return func(*args, **kwargs)
return wrapper
@log_calls
@functools.cache
def double(n):
print(f"computing {n}")
return n * 2
double(4)
double(4)
# calling double(4)
# computing 4
# calling double(4)
cache_layer = double.__wrapped__
original = double.__wrapped__.__wrapped__
print(cache_layer is double) # False
print(original is double) # False
print(inspect.unwrap(double) is original) # True
print(original(4)) # computing 4, then 8The logging wrapper runs on both calls, but computing 4 appears only once because the second result came from the cache. The original function is two hops down. functools.cache and lru_cache also use update_wrapper internally, so a cached function has its own __wrapped__ pointing at the plain function. Calling original(4) skips the cache entirely.
The diagram shows the chain for this example.
Feeding introspection tools. inspect.unwrap(func) follows __wrapped__ links until it reaches an object without one, and returns that object. It raises ValueError if the chain loops back on itself. It also takes an optional stop callable that ends the walk early when the callable returns true for an object.
Signatures follow __wrapped__
The most visible consequence of __wrapped__ is in inspect.signature. By default it follows the chain, so a wrapper that accepts *args, **kwargs reports the signature of the original function:
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, *, timeout=10.0):
"""Open a connection."""
return (host, port, timeout)
print(inspect.signature(connect))
# (host, port=5432, *, timeout=10.0)
print(inspect.signature(connect, follow_wrapped=False))
# (*args, **kwargs)Help displays, IDE tooltips, documentation generators, and frameworks that inspect parameters (dependency injection, command-line builders, web routing) all depend on this. Without __wrapped__, every decorated function would appear to take (*args, **kwargs).
Wrappers that are not functions
update_wrapper works on any object that accepts attribute assignment. This is the main reason to call it directly instead of using wraps. A class-based decorator is the usual case, because you cannot put @wraps on a class instance:
import functools
class CountCalls:
def __init__(self, func):
functools.update_wrapper(self, func)
self.func = func
self.count = 0
def __call__(self, *args, **kwargs):
self.count += 1
return self.func(*args, **kwargs)
@CountCalls
def add(a, b):
"""Add two numbers."""
return a + b
add(1, 2)
add(3, 4)
print(add.count) # 2
print(add.__name__) # add
print(add.__doc__) # Add two numbers.Here update_wrapper(self, func) sets __name__, __doc__, and __wrapped__ on the instance. The instance's __dict__ is also updated with the function's __dict__.
One limitation applies. An instance of CountCalls is not a function and has no __get__ method, so it does not bind self when used on a method inside a class. For decorating methods, prefer a function-based wrapper.
Missing attributes are tolerated, so you can also wrap callables that lack function attributes, such as partial objects:
import functools
p = functools.partial(int, base=2)
def w():
pass
functools.update_wrapper(w, p)
print(w.__name__) # w
print(w.__wrapped__ is p) # TrueA partial object has no __name__, so w keeps its own name. The __wrapped__ link is still set.
Common mistakes
- Forgetting that
wrapstakes the function being wrapped. Writing@functools.wrapswith no call, or@functools.wraps(wrapper), applies it to the wrong object. The argument is always the original function,func. - Applying
wrapsto the outer decorator function. It belongs on the innerwrapper. Putting it onlog_callswould copyfunc's metadata onto the decorator itself. - Treating
__wrapped__as a guarantee. A decorator written withoutwrapsorupdate_wrapperbreaks the chain.inspect.unwrapstops at that layer, and it cannot reach what is underneath. - Expecting the copied
__dict__to be a snapshot. The merge copies entries once, at decoration time. Attributes added to the original later do not appear on the wrapper. - Relying on copied attributes for identity.
wrapper.__name__ == func.__name__is true afterwraps, butwrapper is funcis false. Two wrappers around the same function are different objects.
Exercise
A decorator retry is written with an inner wrapper(*args, **kwargs) but without @functools.wraps. You decorate def fetch(url, timeout=5) with it and call inspect.signature(fetch). What does it report, and what is the smallest change that makes it report (url, timeout=5)?
Show answer
It reports (*args, **kwargs), because fetch is now the wrapper function and has no __wrapped__ link for inspect.signature to follow. Adding @functools.wraps(func) above the inner wrapper fixes it. That sets __wrapped__, and inspect.signature follows it to the original parameters.
Exercise
Given @log_calls stacked on top of @functools.lru_cache(maxsize=32) on a function compute(n), where log_calls uses wraps, write one expression that returns the original, uncached compute function. Then say what inspect.signature(compute, follow_wrapped=False) returns.
Show answer
inspect.unwrap(compute) returns the original function. compute.__wrapped__.__wrapped__ also works here, because there are exactly two layers. With follow_wrapped=False, inspect.signature stops at the outermost wrapper and returns (*args, **kwargs).
Exercise
You write functools.update_wrapper(w, original, assigned=(), updated=()). After the call, which of w.__name__, w.__doc__, and w.__wrapped__ have changed?
Show answer
Only w.__wrapped__ changes. Empty assigned and updated mean no attributes are assigned and no dictionaries are merged, so w keeps its own name and docstring. __wrapped__ is always set to original.