Trace Stacked Decorator Order
Core idea
For @outer above @inner, Python evaluates decorator expressions top to bottom and applies them bottom to top: f = outer(inner(f)). If each wrapper calls its wrapped function once, the outer wrapper starts first and finishes last. Ordering matters when wrappers transform values or manage resources.
def add(fn): return lambda x: fn(x) + 1def times(fn): return lambda x: fn(x) * 2@add@timesdef value(x): return xprint(value(3))print(times(add(lambda x: x))(3))Adding after multiplication differs from multiplying after addition.
Trace calls
def layer(name): def decorate(fn): def wrapper(): print(name, 'in') result = fn() print(name, 'out') return result return wrapper return decorate@layer('A')@layer('B')def task(): print('body')task()Outer A surrounds the entire B call.
Common mistake
Do not assume stacked decorators commute. Cleanup that must run on errors belongs in finally, not merely after a successful call.
Practice
Swap A and B; predict the new trace, then add a finally block to one layer.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Stacked decorators
Check your understanding of stacked decorators.
What is printed?
def a(f): return lambda: f()+3def b(f): return lambda: f()*2@b@adef f(): return 4print(f())What is printed?
def make(n): print(n) return lambda f:f@make(1)@make(2)def f(): passWhich is equivalent to @a above @b?
Which construct ensures cleanup on exceptions?