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, debug and timer, that log information about a function call:
def debug(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
def timer(func):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f" Took {time.time() - start:.2f} seconds")
return result
return wrapper
Now, let's apply them to a function in different orders:
@debug
@timer
def add(a, b):
import time
time.sleep(1)
return a + b
@timer
@debug
def subtract(a, b):
import time
time.sleep(1)
return a - b
When you call add(2, 3) and subtract(2, 3), you'll see that the order of the decorators affects the output: debug will only see the result of timer if it's applied first.
The takeaway is that when stacking Python decorators, the order matters because it determines which decorator's wrapper function gets called first.
Follow me on Dev.to for daily Python tips and quick guides!
💡 Related: **Content Creator Ultimate Bundle (Save 33%)* — $29.99*
💡 Related: **Content Creator Ultimate Bundle (Save 33%)* — $29.99*
Top comments (0)