0
0
PythonHow-ToBeginner · 3 min read

How to Use Multiple Decorators in Python: Syntax and Examples

In Python, you can use multiple decorators by stacking them above a function definition with each decorator on its own line starting with @. The decorators are applied from the closest to the function upwards, meaning the decorator nearest to the function runs first.
📐

Syntax

To use multiple decorators, place each decorator on its own line above the function. The decorator closest to the function is applied first, then the next one above it, and so on.

  • @decorator1 applies first
  • @decorator2 applies second
  • Then the function is defined
python
@decorator2
@decorator1
def function():
    pass
💻

Example

This example shows two decorators that modify a function's output by adding text before and after the original message. It demonstrates how the decorators stack and the order they run.

python
def decorator1(func):
    def wrapper():
        return "Hello, " + func() + "!"
    return wrapper

def decorator2(func):
    def wrapper():
        return func().upper()
    return wrapper

@decorator2
@decorator1
def greet():
    return "world"

print(greet())
Output
HELLO, WORLD!
⚠️

Common Pitfalls

One common mistake is misunderstanding the order decorators are applied. The decorator closest to the function runs first, so the output flows from the inner decorator to the outer.

Another pitfall is forgetting to return the wrapper function inside the decorator, which breaks the chain.

python
def decorator1(func):
    def wrapper():
        return "Hello, " + func() + "!"
    # Missing return wrapper here causes error

@decorator1
@decorator2
def greet():
    return "world"

# This will raise an error because decorator1 returns None

# Correct way:
def decorator1_fixed(func):
    def wrapper():
        return "Hello, " + func() + "!"
    return wrapper
📊

Quick Reference

Remember these tips when using multiple decorators:

  • Stack decorators with @ lines above the function.
  • The decorator closest to the function runs first.
  • Always return the wrapper function inside your decorator.
  • Use decorators to add or modify behavior cleanly.

Key Takeaways

Stack multiple decorators by placing each with @ above the function, closest runs first.
The output of decorators flows from the inner (closest) to the outer (topmost).
Always return the wrapper function inside your decorator to maintain the chain.
Use multiple decorators to combine behaviors cleanly and readably.