返回专栏
· 16 分钟阅读

Python 多层装饰器与带参数装饰器


一、装饰器的基础回顾

在理解多层装饰器和带参数装饰器之前,需要先明确普通装饰器的工作原理。

装饰器本质上是一个接收可调用对象并返回可调用对象的函数。

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))

输出:

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

装饰器语法:

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

等价于:

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


add = log_decorator(add)

执行过程:

  1. 创建原始函数对象。
  2. 将原始函数传递给装饰器。
  3. 装饰器创建包装函数。
  4. 装饰器返回包装函数。
  5. 原函数名称重新绑定到包装函数。
  6. 后续调用通过包装函数执行增强逻辑。

装饰器的实现通常依赖三个基础机制:

  • 高阶函数:函数可以作为参数传递,也可以作为返回值。
  • 闭包:包装函数通过自由变量保存原始函数及配置。
  • 名称重新绑定:原始函数名称指向装饰器返回的对象。

二、什么是多层装饰器

多层装饰器(Multiple Decorators)是指在同一个函数或类上连续应用多个装饰器。

例如:

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()

输出:

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

这里的 decorator_a 和 decorator_b 都作用于同一个函数,但它们并不是同时执行,而是形成嵌套包装结构。

2.1 多层装饰器的等价写法

下面的代码:

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

等价于:

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


hello = decorator_a(decorator_b(hello))

因此,多层装饰器的应用顺序是从下往上:

  1. 首先执行 decorator_b(hello)。
  2. 将返回的包装函数传递给 decorator_a。
  3. decorator_a 再返回外层包装函数。
  4. 最终将 hello 绑定到最外层包装函数。

可以将其理解为:

原始函数
   ↓
decorator_b
   ↓
decorator_a
   ↓
最终函数

2.2 多层装饰器的调用顺序

虽然装饰器的应用顺序是从下往上,但函数调用时的包装层执行顺序恰好相反。

flowchart TD
    A["调用 hello"] --> B["进入 decorator_a"]
    B --> C["进入 decorator_b"]
    C --> D["执行原始函数"]
    D --> E["退出 decorator_b"]
    E --> F["退出 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

可以总结为:

阶段 执行顺序
装饰器应用 从下往上
包装函数进入 从上往下
原始函数执行 最内层
包装函数退出 从下往上

2.3 多层装饰器的洋葱模型

多层装饰器可以理解为洋葱模型。

每个装饰器都在原始函数外部包裹一层逻辑。

例如:

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

等价于:

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

调用时:

log 开始
    auth 开始
        timer 开始
            原始函数
        timer 结束
    auth 结束
log 结束

这种结构适合将不同的横切关注点拆分为独立装饰器。

例如:

  • 日志记录。
  • 权限验证。
  • 性能统计。
  • 缓存处理。
  • 异常处理。
  • 事务管理。

每个装饰器只关注自己的职责,避免将所有增强逻辑堆积在一个函数中。

三、多个装饰器的组合设计

多层装饰器不只是语法组合,还涉及不同功能之间的执行顺序和依赖关系。

3.1 日志与计时装饰器组合

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())

执行过程:

开始执行:calculate
执行耗时:约 0.5 秒
执行完成:calculate
100

这里日志装饰器负责记录函数调用,计时装饰器负责统计执行时间。

两个装饰器各自独立,也可以复用到其他函数上。

3.2 装饰器顺序会影响业务行为

考虑权限校验与缓存组合。

假设:

  • 权限装饰器负责判断用户是否可以访问。
  • 缓存装饰器负责保存函数执行结果。

如果缓存装饰器位于最外层:

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

等价于:

get_sensitive_data = cache_decorator(
    auth_decorator(get_sensitive_data)
)

调用过程:

  1. 先进入缓存装饰器。
  2. 如果缓存命中,可能直接返回缓存结果。
  3. 如果缓存未命中,才进入权限校验装饰器。

这意味着缓存命中时可能跳过权限检查。

如果将权限装饰器放在最外层:

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

则每次调用都会先执行权限检查。

但这仍然不能自动保证缓存安全。缓存键必须考虑用户身份和权限上下文,否则不同用户可能读取到不应共享的数据。

因此,多层装饰器的顺序必须结合业务语义、安全边界和缓存策略进行设计。

四、什么是带参数装饰器

普通装饰器直接接收被装饰函数:

@decorator
def hello():
    pass

但有些场景需要在应用装饰器时提供额外配置。

例如:

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

这里的 max_attempts 和 delay 是装饰器自身的配置参数,而不是原始函数的参数。

这种装饰器称为带参数装饰器(Parameterized Decorator)。

它通常通过额外的一层函数实现。

4.1 带参数装饰器的基本结构

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()

输出:

配置参数:INFO
Hello Python

与普通装饰器相比,带参数装饰器多了一层函数。

函数层级 作用
第一层 接收装饰器配置参数
第二层 接收被装饰函数
第三层 执行包装逻辑

4.2 带参数装饰器的等价写法

下面的代码:

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

等价于:

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


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

也可以直接写成:

hello = decorator_with_args("INFO")(hello)

这说明:

  • decorator_with_args("INFO") 首先执行配置函数。
  • 配置函数返回真正的装饰器。
  • 真正的装饰器接收原始函数。
  • 最终返回包装函数。

4.3 带参数装饰器的执行流程

flowchart TD
    A["定义带参数装饰器"] --> B["传入配置参数"]
    B --> C["执行外层配置函数"]
    C --> D["返回内部装饰器"]
    D --> E["创建原始函数对象"]
    E --> F["将原始函数传给装饰器"]
    F --> G["创建包装函数"]
    G --> H["返回包装函数"]
    H --> I["函数名称重新绑定"]
    I --> J["调用包装函数"]
    J --> K["读取配置参数"]
    K --> L["执行原始函数"]
    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.1 日志级别配置

通过参数控制日志级别:

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())

输出:

[DEBUG] 开始执行 calculate
[DEBUG] 执行完成 calculate
100
[ERROR] 开始执行 process
[ERROR] 执行完成 process
处理完成

同一个装饰器可以通过不同配置实现不同的行为。

5.2 重试装饰器

重试是带参数装饰器非常典型的应用。

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()

这个装饰器允许不同函数配置不同的重试次数和等待时间。

需要注意:

  • 不应该无差别重试所有异常。
  • 不适合对有副作用且非幂等的操作盲目重试。
  • 生产环境应考虑指数退避和随机抖动。
  • 应设置最大总等待时间和请求超时。
  • 重试次数不应该与业务执行次数混淆。

5.3 权限角色装饰器

可以通过参数指定允许访问的角色。

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))

装饰器通过 allowed_roles 保存允许访问的角色集合。

需要注意,示例中的用户对象只是为了演示参数传递。真实系统必须从可信的认证上下文获取用户身份,不能信任调用者随意构造的角色字段。

5.4 缓存容量配置

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())

输出中,第二次相同参数调用会使用缓存结果。

这个示例还展示了一个重要实践:包装函数可以显式暴露内部缓存对象提供的管理接口。

实际使用缓存时,还需要考虑参数可哈希性、缓存过期、数据一致性和并发访问。

六、多层装饰器与带参数装饰器组合

实际开发中,多个装饰器经常需要组合使用,而且其中部分装饰器可能带有配置参数。

例如:

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

这段代码同时使用了:

  • 日志装饰器。
  • 重试装饰器。
  • 性能计时装饰器。

等价于:

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

这里需要区分两个过程:

装饰器应用阶段:

  1. 执行日志配置函数。
  2. 执行重试配置函数。
  3. 将原始函数传入计时装饰器。
  4. 计时装饰器返回包装函数。
  5. 重试装饰器继续包装。
  6. 日志装饰器完成最外层包装。