How do you stack MULTIPLE decorators on the same function, and in what order do they actually execute?
Short answer
Decorators are applied BOTTOM-UP (the one closest to the function definition wraps first), but they EXECUTE top-down at call time, since each decorator's wrapper calls the NEXT one inward — meaning the outermost decorator's 'before' code runs first, and its 'after' code runs…
Advertisement
AModel answer
Decorators are applied BOTTOM-UP (the one closest to the function definition wraps first), but they EXECUTE top-down at call time, since each decorator's wrapper calls the NEXT one inward — meaning the outermost decorator's 'before' code runs first, and its 'after' code runs last.
def bold(func):
def wrapper(): return f"<b>{func()}</b>"
return wrapper
def italic(func):
def wrapper(): return f"<i>{func()}</i>"
return wrapper
@bold
@italic
def text():
return "Hello"
print(text()) # '<b><i>Hello</i></b>' -- italic applied first (closest), then bold wraps around itReal-world example
Combining multiple decorators, like @app.route() and @login_required, and understanding the resulting call order.
Likely follow-ups
- How would swapping the order of @bold and @italic change the final output?
Related topics