Course contentsShow
← Python
Lesson 193 of 1,0603. Functions and ModularizationFree lesson

Implementing Multiple Decorators on Single Functions

Learners will stack multiple decorators to layer complex cross-cutting concerns like logging, timing, and access control onto specific functions.

In this lesson, you will learn how to layer multiple decorators onto a single function to combine different utilities, such as logging, timing, and access control, into a clean, modular pipeline.

The Power of Stacking

When you decorate a function, you are essentially wrapping it in a new layer of logic. Python allows you to "stack" these layers by placing multiple @decorator lines directly above your function definition. When you call the decorated function, Python executes these wrappers from the bottom up (closest to the function first).

Think of it like getting dressed in the winter: you put on your shirt first, then your sweater, then your coat. Each layer adds a specific feature without you needing to change your actual clothes.

Concrete Example

Imagine you want to log every time a function runs, and you also want to time how long it takes to execute. Instead of writing that logic inside your function, you can stack two distinct decorators:

def logger(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"Execution time: {time.time() - start:.4f}s")
        return result
    return wrapper

@logger
@timer
def process_data():
    print("Processing...")

process_data()

Why order matters

In the code above, @timer is closest to the function, so it runs first, capturing the timing logic. The @logger wraps that entire process, meaning it logs the initiation of the timing operation. If you swap the order, you change the sequence of execution. Because decorators effectively call the function below them, stacking them allows you to cleanly separate cross-cutting concerns—like security, performance tracking, and logging—without cluttering your core business logic. This makes your code highly readable and incredibly easy to maintain or expand later.

Key Takeaway: Stacking multiple decorators allows you to layer complex, reusable behaviors onto your functions by applying them from the bottom up.