Sub topic 7
Stacking decorators and the order they apply
This chapter assumes you can write a basic decorator that forwards *args and **kwargs. It also assumes you know the @ syntax and why functools.wraps is used. Here you learn what happens when one function carries two or more decorators, and which decorator runs first.
Stacking is nested reassignment
You can put several decorator lines above one function. Python applies them from the bottom up, starting with the decorator closest to def. Each decorator receives the result of the one below it.
import functools
def bold(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return "<b>" + func(*args, **kwargs) + "</b>"
return wrapper
def italic(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return "<i>" + func(*args, **kwargs) + "</i>"
return wrapper
@bold
@italic
def greet():
return "hi"
print(greet()) # <b><i>hi</i></b>The stacked form is shorthand for nested reassignment:
def greet():
return "hi"
greet = bold(italic(greet))italic wraps the original greet first. bold then wraps the function that italic returned. The name greet ends up pointing at the outermost wrapper, which is the one from bold.
Two different orders
Stacking involves two orders that are easy to confuse:
- Decoration time is when the
defstatement runs, usually at import. Decorators are applied bottom-up. - Call time is when you call the function. Wrappers run top-down on the way in, then unwind bottom-up on the way out.
The following code makes both visible. The factory trace prints when it is called, when it decorates, and when the wrapper runs.
import functools
def trace(label):
print(f"building {label}")
def decorator(func):
print(f"decorating with {label}")
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"enter {label}")
result = func(*args, **kwargs)
print(f"exit {label}")
return result
return wrapper
return decorator
@trace("A")
@trace("B")
def work():
print("working")
print("--- calling ---")
work()The output is:
building A
building B
decorating with B
decorating with A
--- calling ---
enter A
enter B
working
exit B
exit AThe output shows three separate phases:
- The decorator expressions,
trace("A")andtrace("B"), are evaluated top-down. That is why "building" appears A first. - The resulting decorators are applied bottom-up. B decorates
work, then A decorates B's wrapper. - At call time you enter through the outermost wrapper (A) and reach the original function last. The returns unwind in the reverse order.
A useful mental model: the top decorator is the outermost layer. It sees the call first and the result last. The bottom decorator sits closest to your code.
Why the order changes behavior
If two decorators are independent, swapping them changes nothing visible. Most real decorators are not independent, because one of them can stop a call, change its arguments, or change its result. Consider a logging decorator and an access check:
import functools
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"call: {func.__name__}")
return func(*args, **kwargs)
return wrapper
def require_admin(func):
@functools.wraps(func)
def wrapper(user, *args, **kwargs):
if user != "admin":
raise PermissionError(f"{user} is not allowed")
return func(user, *args, **kwargs)
return wrapper
@log_calls
@require_admin
def delete_all(user):
return "deleted"
@require_admin
@log_calls
def purge(user):
return "purged"
for fn in (delete_all, purge):
try:
fn("guest")
except PermissionError as exc:
print("denied:", exc)The output is:
call: delete_all
denied: guest is not allowed
denied: guest is not allowedIn delete_all, logging is outermost, so the rejected attempt is logged before the check runs. In purge, the check is outermost and raises before the logging wrapper is ever reached. Neither is wrong, but they answer different questions. The first records every attempt. The second records only the attempts that were allowed.
The same reasoning applies to other combinations:
| Pair (top, then bottom) | What it does |
|---|---|
| `timer` above `lru_cache` | Times every call, including fast cache hits |
| `lru_cache` above `timer` | Times only real computations, because hits never reach the timer |
| `retry` above `log_calls` | Logs each attempt, since each retry calls the logged function again |
| `log_calls` above `retry` | Logs once per top-level call, however many retries happen inside |
| Registration above a wrapper | Registers the wrapped version |
| Registration below a wrapper | Registers the raw function |
As a rule of thumb, ask what each decorator needs to see. A decorator that must observe failures or rejected calls goes outside the one that produces them. A decorator that should only act on valid input goes inside the one that validates.
Registration decorators and order
A decorator that records a function in a registry usually returns the function unchanged. Where it sits in the stack decides which object gets stored.
ROUTES = {}
def route(path):
def decorator(func):
ROUTES[path] = func
return func
return decorator
def shout(func):
def wrapper():
return func().upper()
return wrapper
@route("/a")
@shout
def page_a():
return "page a"
@shout
@route("/b")
def page_b():
return "page b"
print(ROUTES["/a"]()) # PAGE A
print(ROUTES["/b"]()) # page bFor /a, route receives the wrapper from shout, so the stored function shouts. For /b, route runs first and stores the original function, and shout wraps it afterward without the registry knowing. This is a common source of "my decorator is ignored" bugs in frameworks that use registration.
One broken link breaks the chain
Stacking makes functools.wraps more important. Each decorator copies metadata from the function it receives. If one decorator in the middle forgets wraps, everything above it copies the wrong metadata.
import functools
def plain(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
def polite(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@polite
@plain
def hello():
"""Say hello."""
print(hello.__name__) # wrapper
print(hello.__doc__) # Nonepolite did its job correctly. It copied the name and docstring from what it was given, but plain had already replaced them with the name wrapper and no docstring. The original information is gone from the visible attributes.
When every decorator uses wraps, each wrapper also gets a __wrapped__ attribute that points one layer down. inspect.unwrap(func) follows these links to the original function, which helps when you need to inspect the real signature. A missing wraps anywhere breaks that chain too.
Debugging a stack
When a stacked function behaves unexpectedly, these steps usually find the cause:
- Write out the equivalent nested call, such as
a(b(c(func))), and read it from the inside out. - Print
func.__name__inside each decorator, or use atracedecorator like the one above, to see the actual order. - Check each decorator for
functools.wraps. - Look at the signature each wrapper expects. In
require_admin, the wrapper assumes the first argument is the user. If another decorator changes the arguments before it, the check fails in confusing ways. - Keep stacks short. More than three or four decorators on one function is a signal to combine some of them or to compose them explicitly.
If you reuse the same stack in many places, you can combine decorators into one:
def stack(*decorators):
def combined(func):
for decorator in reversed(decorators):
func = decorator(func)
return func
return combined
@stack(log_calls, require_admin)
def archive(user):
return "archived"Here stack(log_calls, require_admin) is equivalent to writing @log_calls above @require_admin. The loop uses reversed so that the first decorator in the list ends up outermost, which matches how you would read the stacked lines.
Exercise
Given @a, @b, @c written in that order above def f(), which equivalent assignment does Python run, and in what order do the wrappers execute when you call f()?
Show answer
Python runs f = a(b(c(f))), applying c first, then b, then a. On a call, the wrapper from a runs first, then b, then c, then the original f. The returns unwind in the reverse order, c, b, a.
Exercise
You have a timer decorator and functools.lru_cache. You want the timer to report only the cost of real computations, not cache hits. Which one goes on top, and why?
Show answer
Put lru_cache on top and timer below it. A cache hit is answered by the outer lru_cache wrapper and never reaches the inner timer, so only real computations are timed. If timer were on top, it would time every call, including the fast cache hits.