Stacking Multiple Decorators
Stacking decorators executes them from bottom to top (inside-out). `@dec_a` on top of `@dec_b` on `func` behaves as `dec_a(dec_b(func))` 🥞.
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 message():
return "Python"
print(message()) # <b><i>Python</i></b> 🥞
# 37. Stacking Multiple Decorators Stacking decorators executes them from bottom to top (inside-out). `@dec_a` on top of `@dec_b` on `func` behaves as `dec_a(dec_b(func))` 🥞. ```python 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 message(): return "Python" print(message()) # <b><i>Python</i></b> 🥞 ``` Bottom decorator wraps first; top decorator wraps the wrapper. Think of putting on socks before putting on shoes — order matters! 🥞 --- ### Question In what order do stacked decorators wrap a function? 🧠- [ ] a. Bottom-to-top: the decorator closest to the function wraps first 🥞 - [ ] b. Top-to-bottom: the top decorator executes and discards lower ones - [ ] c. Simultaneously across independent worker threads - [ ] d. Alphabetically based on decorator function names --- ### Challenge Write decorator `add_stars(func)` wrapping return value with `f'***{func()}***'`, and `add_brackets(func)` wrapping with `f'[{func()}]'`. Stack `@add_brackets` above `@add_stars` on `def get_text(): return 'CODE'`. Print `get_text()`. 🎯 <details> <summary>Solution</summary> ```python def add_stars(func): def wrapper(): return f"***{func()}***" return wrapper def add_brackets(func): def wrapper(): return f"[{func()}]" return wrapper @add_brackets @add_stars def get_text(): return "CODE" print(get_text()) ``` </details>