Back to series
· 7 min read

Python Multi-layer Decorators and Decorators with Parameters


1. Basic Review of Decorators

Before understanding multiple decorators and decorators with arguments, it is necessary to clarify how ordinary decorators work.

A decorator is essentially a function that takes a callable object and returns a callable object.

def log_decorator(func):
    def wrapper(*args, **kwargs):
        print("函数开始执行")
        result = func(*args, **kwargs)
        print("函数执行结束")
        return result

    return wrapper


@log_decorator
def add(a, b):
    return a + b


print(add(10, 20))

Output:

函数开始执行
函数执行结束
30

Decorator syntax:

@log_decorator
def add(a, b):
    return a + b

is equivalent to:

def add(a, b):
    return a + b


add = log_decorator(add)

Execution process:

  1. Create the original function object.
  2. Pass the original function to the decorator.
  3. The decorator creates a wrapper function.
  4. The decorator returns the wrapper function.
  5. The original function name is rebound to the wrapper function.
  6. Subsequent calls execute the enhanced logic through the wrapper function.

Decorator implementations usually rely on three fundamental mechanisms:

  • Higher-order functions: functions can be passed as arguments and returned as values.
  • Closures: the wrapper function stores the original function and configuration through free variables.
  • Name rebinding: the original function name points to the object returned by the decorator.

2. What Are Multiple Decorators

Multiple Decorators refers to applying several decorators consecutively to the same function or class.

For example:

def decorator_a(func):
    def wrapper(*args, **kwargs):
        print("A 开始")
        result = func(*args, **kwargs)
        print("A 结束")
        return result

    return wrapper


def decorator_b(func):
    def wrapper(*args, **kwargs):
        print("B 开始")
        result = func(*args, **kwargs)
        print("B 结束")
        return result

    return wrapper


@decorator_a
@decorator_b
def hello():
    print("Hello Python")


hello()

Output:

A 开始
B 开始
Hello Python
B 结束
A 结束

Here, decorator_a and decorator_b both apply to the same function, but they do not execute at the same time; instead, they form a nested wrapping structure.

2.1 Equivalent Form of Multiple Decorators

The following code:

@decorator_a
@decorator_b
def hello():
    print("Hello Python")

is equivalent to:

def hello():
    print("Hello Python")


hello = decorator_a(decorator_b(hello))

Therefore, multiple decorators are applied from bottom to top:

  1. First, decorator_b(hello) is executed.
  2. The returned wrapper function is passed to decorator_a.
  3. decorator_a then returns the outer wrapper function.
  4. Finally, hello is bound to the outermost wrapper function.

This can be understood as:

Original function
   ↓
decorator_b
   ↓
decorator_a
   ↓
Final function

2.2 Call Order of Multiple Decorators

Although decorators are applied from bottom to top, the execution order of the wrapper layers when the function is called is exactly the opposite.

flowchart TD
    A["Call hello"] --> B["Enter decorator_a"]
    B --> C["Enter decorator_b"]
    C --> D["Execute original function"]
    D --> E["Exit decorator_b"]
    E --> F["Exit decorator_a"]
    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

This can be summarized as:

Stage Execution order
Decorator application Bottom to top
Wrapper function entry Top to bottom
Original function execution Innermost layer
Wrapper function exit Bottom to top

2.3 The Onion Model of Multi-layer Decorators

Multi-layer decorators can be understood as an onion model.

Each decorator wraps a layer of logic around the original function.

For example:

@log_decorator
@auth_decorator
@timer_decorator
def execute():
    print("执行业务逻辑")

This is equivalent to:

execute = log_decorator(
    auth_decorator(
        timer_decorator(execute)
    )
)

When called:

log start
    auth start
        timer start
            Original function
        timer end
    auth end
log end

This structure is suitable for splitting different cross-cutting concerns into independent decorators.

For example:

  • Logging.
  • Permission verification.
  • Performance statistics.
  • Caching.
  • Exception handling.
  • Transaction management.

Each decorator focuses only on its own responsibility, avoiding piling all enhancement logic into a single function.

3. Combined Design of Multiple Decorators

Multi-layer decorators are not merely a syntactic combination; they also involve the execution order and dependencies among different functions.

3.1 Combining Logging and Timing Decorators

from functools import wraps
import time


def log_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        print(f"开始执行:{func.__name__}")
        result = func(*args, **kwargs)
        print(f"执行完成:{func.__name__}")
        return result

    return wrapper


def timer_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()

        try:
            return func(*args, **kwargs)
        finally:
            elapsed = time.perf_counter() - start
            print(f"执行耗时:{elapsed:.6f} 秒")

    return wrapper


@log_decorator
@timer_decorator
def calculate():
    time.sleep(0.5)
    return 100


print(calculate())

Execution process:

Start executing: calculate
Execution time: about 0.5 seconds
Execution complete: calculate
100

Here, the logging decorator is responsible for recording function calls, and the timing decorator is responsible for measuring execution time.

The two decorators are independent and can also be reused on other functions.

3.2 Decorator Order Affects Business Behavior

Consider a combination of permission checking and caching.

Suppose:

  • The permission decorator determines whether a user can access.
  • The cache decorator saves the function execution result.

If the cache decorator is on the outermost layer:

@cache_decorator
@auth_decorator
def get_sensitive_data(user):
    return "敏感数据"

This is equivalent to:

get_sensitive_data = cache_decorator(
    auth_decorator(get_sensitive_data)
)

Call flow:

  1. The cache decorator is entered first.
  2. If the cache hits, the cached result may be returned directly.
  3. Only if the cache misses is the authorization check decorator entered.

This means that the authorization check may be skipped when the cache hits.

If the authorization decorator is placed on the outermost layer:

@auth_decorator
@cache_decorator
def get_sensitive_data(user):
    return "敏感数据"

Then every call will perform the authorization check first.

However, this still does not automatically guarantee cache security. The cache key must account for user identity and authorization context; otherwise, different users may read data that should not be shared.

Therefore, the order of multiple decorators must be designed in light of business semantics, security boundaries, and caching strategy.

4. What Is a Parameterized Decorator

A regular decorator directly receives the function being decorated:

@decorator
def hello():
    pass

However, some scenarios require additional configuration to be provided when applying the decorator.

For example:

@retry(max_attempts=3, delay=1)
def request_data():
    pass

Here, max_attempts and delay are configuration parameters of the decorator itself, not parameters of the original function.

This kind of decorator is called a parameterized decorator.

It is usually implemented with an extra layer of functions.

4.1 Basic Structure of a Parameterized Decorator

def decorator_with_args(option):

    def decorator(func):

        def wrapper(*args, **kwargs):
            print(f"配置参数:{option}")
            return func(*args, **kwargs)

        return wrapper

    return decorator


@decorator_with_args("INFO")
def hello():
    print("Hello Python")


hello()

Output:

Configuration parameter: INFO
Hello Python

Compared with a regular decorator, a parameterized decorator has one extra layer of functions.

Function layer Role
First layer Receives the decorator configuration parameters
Second layer Receives the decorated function
Third layer Executes the wrapping logic

4.2 Equivalent Forms of a Parameterized Decorator

The following code:

@decorator_with_args("INFO")
def hello():
    print("Hello Python")

is equivalent to:

def hello():
    print("Hello Python")


decorator = decorator_with_args("INFO")
hello = decorator(hello)

It can also be written directly as:

hello = decorator_with_args("INFO")(hello)

This shows that:

  • decorator_with_args("INFO") executes the configuration function first.
  • The configuration function returns the actual decorator.
  • The actual decorator receives the original function.
  • Finally, it returns the wrapper function.

4.3 Execution Flow of a Parameterized Decorator

flowchart TD
    A["Define decorator with parameters"] --> B["Pass configuration parameters"]
    B --> C["Execute outer configuration function"]
    C --> D["Return inner decorator"]
    D --> E["Create original function object"]
    E --> F["Pass original function to decorator"]
    F --> G["Create wrapper function"]
    G --> H["Return wrapper function"]
    H --> I["Rebind function name"]
    I --> J["Call wrapper function"]
    J --> K["Read configuration parameters"]
    K --> L["Execute original function"]
    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style G fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style J fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style K fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style L fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

5. Typical Implementation of Decorators with Parameters

5.1 Log Level Configuration

Control the log level through parameters:

from functools import wraps


def log(level="INFO"):

    def decorator(func):

        @wraps(func)
        def wrapper(*args, **kwargs):
            print(f"[{level}] 开始执行 {func.__name__}")

            result = func(*args, **kwargs)

            print(f"[{level}] 执行完成 {func.__name__}")
            return result

        return wrapper

    return decorator


@log("DEBUG")
def calculate():
    return 100


@log("ERROR")
def process():
    return "处理完成"


print(calculate())
print(process())

Output:

[DEBUG] Start executing calculate
[DEBUG] Finished executing calculate
100
[ERROR] Start executing process
[ERROR] Finished executing process
Processing complete

By using different configurations, the same decorator can achieve different behaviors.

5.2 Retry Decorator

Retry is a very typical use case for decorators with parameters.

import time
from functools import wraps


def retry(max_attempts=3, delay=1):

    if max_attempts < 1:
        raise ValueError("max_attempts 必须大于零")

    if delay < 0:
        raise ValueError("delay 不能小于零")

    def decorator(func):

        @wraps(func)
        def wrapper(*args, **kwargs):
            for attempt in range(max_attempts):
                try:
                    return func(*args, **kwargs)

                except ConnectionError:
                    if attempt == max_attempts - 1:
                        raise

                    time.sleep(delay)

        return wrapper

    return decorator


@retry(max_attempts=3, delay=1)
def request_data():
    print("请求远程服务")
    raise ConnectionError("连接失败")


request_data()

This decorator allows different functions to configure different retry counts and wait times.

Note the following:

  • Do not retry all exceptions indiscriminately.
  • Blind retries are not suitable for operations with side effects that are not idempotent.
  • Production environments should consider exponential backoff and random jitter.
  • A maximum total wait time and request timeout should be set.
  • The retry count should not be confused with the number of business executions.

5.3 Permission Role Decorator

The roles allowed to access can be specified via parameters.

from functools import wraps


def require_role(*allowed_roles):

    def decorator(func):

        @wraps(func)
        def wrapper(user, *args, **kwargs):
            role = user.get("role")

            if role not in allowed_roles:
                raise PermissionError("当前用户无权访问")

            return func(user, *args, **kwargs)

        return wrapper

    return decorator


@require_role("admin", "operator")
def delete_record(user, record_id):
    return f"删除记录:{record_id}"


user = {"role": "admin"}

print(delete_record(user, 1001))

The decorator uses allowed_roles to store the set of roles allowed to access.

Note that the user object in the example is only for demonstrating parameter passing. A real system must obtain the user identity from a trusted authentication context and must not trust role fields arbitrarily constructed by the caller.

5.4 Cache Capacity Configuration

from functools import lru_cache, wraps


def cache(maxsize=128):

    def decorator(func):
        cached_func = lru_cache(maxsize=maxsize)(func)

        @wraps(func)
        def wrapper(*args, **kwargs):
            return cached_func(*args, **kwargs)

        wrapper.cache_info = cached_func.cache_info
        wrapper.cache_clear = cached_func.cache_clear

        return wrapper

    return decorator


@cache(maxsize=64)
def calculate(number):
    print("执行计算")
    return number ** 2


print(calculate(10))
print(calculate(10))
print(calculate.cache_info())

In the output, the second call with the same arguments uses the cached result.

This example also demonstrates an important practice: the wrapper function can explicitly expose the management interfaces provided by the internal cache object.

When actually using caching, you also need to consider argument hashability, cache expiration, data consistency, and concurrent access.

Six. Combining Multi-layer Decorators and Decorators with Parameters

In real-world development, multiple decorators often need to be used together, and some of them may have configuration parameters.

For example:

@log(level="INFO")
@retry(max_attempts=3, delay=1)
@measure_time
def request_data():
    print("请求远程数据")
    return {"status": "success"}

This code uses all of the following at the same time:

  • A logging decorator.
  • A retry decorator.
  • A performance timing decorator.

It is equivalent to:

request_data = log(level="INFO")(
    retry(max_attempts=3, delay=1)(
        measure_time(request_data)
    )
)

Two processes need to be distinguished here:

Decorator application stage:

  1. Execute the logging configuration function.
  2. Execute the retry configuration function.
  3. Pass the original function into the timing decorator.
  4. The timing decorator returns a wrapper function.
  5. The retry decorator continues wrapping.
  6. The logging decorator completes the outermost wrapping.