DEV Community

qing
qing

Posted on

TIL: Python Decorators Can Stack — And the Order Matters (2026)

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 powerful tool for code reuse and simplification. But what really caught my attention was that the order in which you stack them actually matters.

Let's take a look at an example with two simple decorators:

def decorator1(func):
    def wrapper():
        print("Decorator 1: Before function call")
        func()
        print("Decorator 1: After function call")
    return wrapper

def decorator2(func):
    def wrapper():
        print("Decorator 2: Before function call")
        func()
        print("Decorator 2: After function call")
    return wrapper

@decorator1
@decorator2
def say_hello():
    print("Hello!")

say_hello()
Enter fullscreen mode Exit fullscreen mode

When you run this code, you'll see that the output is:

Decorator 1: Before function call
Decorator 2: Before function call
Hello!
Decorator 2: After function call
Decorator 1: After function call
Enter fullscreen mode Exit fullscreen mode

As you can see, the decorators are executed in reverse order, with the closest one to the function being executed first. This is because each decorator is wrapping the result of the previous one, so decorator1 is wrapping the result of decorator2.

The takeaway is: when stacking Python decorators, the order in which you apply them can significantly impact the behavior of your code.


Follow me on Dev.to for daily Python tips and quick guides!


💡 Related: **Content Creator Ultimate Bundle (Save 33%)* — $30*


💡 Related: **Content Creator Ultimate Bundle (Save 33%)* — $29.99*

Top comments (0)