Sub topic 7
Stacking decorators and the order they apply
This chapter assumes you can write a basic decorator with functools.wraps and that you know the @ syntax is shorthand for reassignment. Here you will see what happens when you put more than one decorator on the same function.
Stacking is nested reassignment
You can place several decorator lines above one function:
@bold
@italic
def greet():
return "hi"Python reads this as nested calls:
greet = bold(italic(greet))The decorator closest to the function, @italic, is applied first. It wraps the original greet. Then @bold wraps the result. So decorators are applied from the bottom up.
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 output has <b> on the outside. The outermost wrapper, bold's, runs first when you call greet(). It calls the italic wrapper, which calls the real function.
Two orders to keep apart
Stacking involves two different orders:
- Decoration time runs once, when the
defstatement executes. It goes bottom to top. - Call time runs on every call. It goes top to bottom on the way in, then bottom to top on the way out.
A tracing decorator makes both visible:
import functools
def tag(name):
def decorator(func):
print(f"decorating {func.__name__} with {name}")
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"enter {name}")
result = func(*args, **kwargs)
print(f"exit {name}")
return result
return wrapper
return decorator
@tag("outer")
@tag("inner")
def work():
print("working")
print("--- calling ---")
work()Output:
decorating work with inner
decorating work with outer
--- calling ---
enter outer
enter inner
working
exit inner
exit outerThe two "decorating" lines appear before any call, with inner first. Each call then enters from the outside and unwinds in reverse, like nested function calls.
Why order changes behavior
Order only affects the result when the decorators interact. Swapping bold and italic changes the nesting of the tags. Other pairs matter more:
| Stack (top to bottom) | Effect |
|---|---|
| `@timer` over `@lru_cache` | The timer measures every call, including fast cache hits. |
| `@lru_cache` over `@timer` | The timer runs only on cache misses, so it measures real computation. |
| `@require_login` over `@log_calls` | Rejected requests are never logged. |
| `@log_calls` over `@require_login` | Every attempt is logged, including rejected ones. |
A useful rule is that the outer decorator sees and controls everything the inner ones do. Put the decorator that must run first, or must see every call, at the top.
Stacking and metadata
With functools.wraps in every layer, the metadata passes up through the whole stack. Each wrapper copies __name__ and __doc__ from the one below it and sets __wrapped__ to point at it. If one decorator in the stack omits wraps, the function's name and docstring are lost from that point up. Every decorator above it then copies the wrong name. One careless decorator can therefore spoil the metadata for the whole stack.
Exercise
In the bold/italic example, you swap the two lines so @italic is on top and @bold is directly above def greet(). What does greet() return?
Show answer
<i><b>hi</b></i>. The decorator nearest the function, bold, is applied first and wraps the original. italic then wraps that result, so <i> ends up on the outside.
Exercise
A function is decorated with @timer above @lru_cache(maxsize=None). You call it twice with the same arguments. How many times does the timer report, and does it measure the computation both times?
Show answer
The timer reports twice, because it is the outer decorator and runs on every call. Only the first measurement includes the computation. The second measures a cache hit, which is much faster.