TIL: Python Decorators Can Stack — And the Order Matters
As I dove deeper into Python, I discovered that decorators can be stacked on top of each other, which can be a game-changer for code organization and reuse. But what really caught my attention was that the order of these stacked decorators actually matters.
Let's consider a simple example with two decorators: debug and timer. The debug decorator prints out the input arguments and return value of a function, while the timer decorator calculates the execution time of a function.
import time
from functools import wraps
def debug(func):
@wraps(func)
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
print(f"Input: {args}, {kwargs}, Output: {result}")
return result
return wrapper
def timer(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"Execution time: {end - start} seconds")
return result
return wrapper
@debug
@timer
def add(a, b):
time.sleep(1) # simulate some work
return a + b
add(2, 3)
In this example, timer is applied first, followed by debug. This means that the timer decorator will wrap the original add function, and then the debug decorator will wrap the result of timer. As a result, the execution order will be: timer starts, add function executes, timer ends, and finally debug prints out the input and output.
The takeaway is that when stacking decorators in Python, the order in which they are applied can significantly affect the behavior of your code.
Follow me on Dev.to for daily Python tips and quick guides!
🛠️ Useful resource: **Content Creator Ultimate Bundle (Save 33%)* — $29.99. Check it out on Gumroad!*
喜欢这篇文章?关注获取更多Python自动化内容!
Top comments (0)