TIL: Python Decorators Can Stack — And the Order Matters
Hey fellow devs, today I learned something cool about Python decorators: they can be stacked, and the order in which you stack them actually matters. Let's take a look at an example to see what I mean.
Suppose we have two simple decorators, decorator_a and decorator_b, that just print a message before and after the function they're decorating is called:
def decorator_a(func):
def wrapper():
print("Decorator A: before")
func()
print("Decorator A: after")
return wrapper
def decorator_b(func):
def wrapper():
print("Decorator B: before")
func()
print("Decorator B: after")
return wrapper
@decorator_a
@decorator_b
def say_hello():
print("Hello!")
When we call say_hello(), here's what happens:
Decorator A: before
Decorator B: before
Hello!
Decorator B: after
Decorator A: after
As you can see, the decorators are executed in reverse order - decorator_b is applied first, then decorator_a. This makes sense, since decorator_a is the outermost decorator, wrapping the result of decorator_b.
The key takeaway is that when stacking Python decorators, the order of execution is determined by the order in which they are applied, from bottom to top.
Follow me on Dev.to for daily Python tips and quick guides!
💡 Related: **Content Creator Ultimate Bundle (Save 33%)* — $29.99*
Top comments (0)