返回专栏
· 17 分钟阅读

Python 装饰器的基本原理


一、什么是装饰器

装饰器(Decorator)是一种用于扩展函数或类行为的机制。它通常接收一个可调用对象作为参数,经过处理后返回另一个可调用对象。

装饰器的核心思想是:不直接修改原函数,而是在原函数外部增加一层包装逻辑。

例如:

def log_decorator(func):
    def wrapper():
        print("函数开始执行")
        func()
        print("函数执行结束")

    return wrapper


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


say_hello = log_decorator(say_hello)

say_hello()

输出:

函数开始执行
Hello Python
函数执行结束

这段代码中:

  1. say_hello 是原始函数。
  2. log_decorator 接收原始函数作为参数。
  3. wrapper 是负责增强行为的包装函数。
  4. wrapper 在执行过程中调用原始函数。
  5. log_decorator 返回包装函数。
  6. say_hello 最终指向包装函数。

原始函数的业务逻辑没有发生变化,但调用时增加了额外行为。

1.1 装饰器的本质

从本质上看,装饰器是一种高阶函数。

高阶函数满足以下任意一个条件:

  • 接收函数或其他可调用对象作为参数。
  • 返回函数或其他可调用对象。

装饰器通常同时满足这两个条件:

def decorator(func):
    def wrapper():
        return func()

    return wrapper

其中:

  • decorator 接收函数对象。
  • wrapper 是内部函数。
  • wrapper 引用外层变量 func,形成闭包。
  • decorator 返回 wrapper 函数对象。

因此,Python 中常见的函数装饰器实际上结合了高阶函数、闭包和函数对象等机制。

二、装饰器的基本语法

Python 提供了 @ 语法糖,用于简化装饰器的应用。

例如:

def log_decorator(func):
    def wrapper():
        print("函数开始执行")
        func()
        print("函数执行结束")

    return wrapper


@log_decorator
def say_hello():
    print("Hello Python")


say_hello()

输出:

函数开始执行
Hello Python
函数执行结束

这里的:

@log_decorator
def say_hello():
    print("Hello Python")

等价于:

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


say_hello = log_decorator(say_hello)

也就是说,@decorator 并不是一种特殊的函数定义方式,而是 Python 提供的装饰器应用语法。

2.1 装饰器的执行时机

装饰器与普通函数调用有一个重要区别:装饰器表达式通常在函数定义阶段执行,而不是每次调用函数时执行。

def decorator(func):
    print("装饰器开始执行")

    def wrapper():
        print("包装函数执行")
        return func()

    return wrapper


@decorator
def hello():
    print("Hello")


print("程序继续执行")
hello()
hello()

输出:

装饰器开始执行
程序继续执行
包装函数执行
Hello
包装函数执行
Hello

可以观察到:

  • 定义 hello 时,装饰器执行一次。
  • 装饰器返回包装函数。
  • 每次调用 hello(),执行的是包装函数。
  • 包装函数内部再调用原始函数。

因此,装饰器的应用时机和包装函数的调用时机是两个不同的阶段。

2.2 装饰器执行流程

flowchart TD
    A["解释器执行函数定义"] --> B["创建原始函数对象"]
    B --> C["调用装饰器"]
    C --> D["传入原始函数对象"]
    D --> E["创建包装函数"]
    E --> F["返回包装函数"]
    F --> G["重新绑定函数名称"]
    G --> H["后续调用包装函数"]
    H --> I["执行增强逻辑"]
    I --> J["调用原始函数"]
    J --> K["返回执行结果"]
    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:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style H fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style I fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style J fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style K fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

三、装饰器的底层实现原理

理解装饰器,首先需要掌握 Python 的几个基础机制。

3.1 函数是一等对象

Python 中,函数本身也是对象。

函数可以:

  • 赋值给变量。
  • 作为参数传递。
  • 作为函数返回值。
  • 存储在列表、字典等容器中。
  • 在运行时动态创建和替换。

例如:

def greet():
    return "Hello"


another_greet = greet

print(another_greet())
print(greet is another_greet)

输出:

Hello
True

another_greet 和 greet 引用的是同一个函数对象。

装饰器正是利用函数可以作为参数和返回值的特性实现的。

3.2 闭包保存原始函数

装饰器中的包装函数通常需要调用原始函数。

def decorator(func):

    def wrapper():
        print("执行前")
        result = func()
        print("执行后")
        return result

    return wrapper

这里的 func 定义在 decorator() 中,却被内部函数 wrapper() 使用。

因此,func 对 wrapper() 来说是自由变量。

当 decorator() 返回 wrapper 后,闭包机制使包装函数仍然能够访问原始函数对象。

这意味着即使装饰器函数执行结束,包装函数仍然可以调用原始函数。

3.3 名称重新绑定

考虑以下代码:

def decorator(func):
    def wrapper():
        print("Before")
        return func()

    return wrapper


def hello():
    print("Hello")


hello = decorator(hello)

执行最后一行时:

  1. Python 将原始 hello 函数对象传入 decorator。
  2. decorator 创建 wrapper。
  3. wrapper 通过闭包保存对原始 hello 的引用。
  4. decorator 返回 wrapper。
  5. 名称 hello 被重新绑定到包装函数。

因此,后续调用:

hello()

实际上执行的是 wrapper()。

可以用以下关系理解:

flowchart TD
    A["原始函数 hello"] --> B["传入 decorator"]
    B --> C["包装函数 wrapper"]
    C --> D["闭包引用原始函数"]
    C --> E["返回 wrapper"]
    E --> F["hello 重新绑定"]
    F --> G["调用 hello"]
    G --> H["实际执行 wrapper"]
    H --> I["调用原始 hello"]
    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style H fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

四、编写通用装饰器

前面的装饰器只能处理没有参数的函数。

实际业务中,函数可能接收位置参数、关键字参数,也可能返回不同类型的数据。

因此,通用装饰器通常使用 *args 和 **kwargs。

4.1 支持任意参数

def log_decorator(func):

    def wrapper(*args, **kwargs):
        print(f"调用函数:{func.__name__}")

        return func(*args, **kwargs)

    return wrapper


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


@log_decorator
def greet(name, message="Hello"):
    return f"{message}, {name}"


print(add(10, 20))
print(greet("Python"))

输出:

调用函数:add
30
调用函数:greet
Hello, Python

这里:

  • *args 接收任意数量的位置参数。
  • **kwargs 接收任意数量的关键字参数。
  • func(*args, **kwargs) 将参数重新传递给原始函数。

这样,装饰器就不需要提前知道原始函数的参数结构。

4.2 保留原始函数返回值

包装函数应该正确返回原始函数的执行结果。

不推荐:

def decorator(func):
    def wrapper(*args, **kwargs):
        func(*args, **kwargs)

    return wrapper

这种写法会丢弃原始函数的返回值。

推荐:

def decorator(func):
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        return result

    return wrapper

也可以简化为:

def decorator(func):
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)

    return wrapper

对于通用装饰器,保留返回值是非常重要的设计原则。

4.3 保留异常传播行为

包装函数调用原始函数时,如果原始函数抛出异常,通常应该让异常继续向调用方传播。

def log_decorator(func):
    def wrapper(*args, **kwargs):
        print("函数开始执行")

        try:
            return func(*args, **kwargs)
        except Exception as exc:
            print(f"函数执行失败:{exc}")
            raise
        finally:
            print("函数执行结束")

    return wrapper


@log_decorator
def divide(a, b):
    return a / b


print(divide(10, 2))

输出:

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

如果除数为零,异常会被记录后继续抛出。

这里使用 raise 而不是 raise exc,可以保留原始异常的传播语义和更完整的追踪信息。

五、functools.wraps 的作用

使用装饰器后,函数名称、文档字符串等元信息可能发生变化。

例如:

def decorator(func):
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)

    return wrapper


@decorator
def add(a, b):
    """计算两个数的和"""
    return a + b


print(add.__name__)
print(add.__doc__)

输出:

wrapper
None

原因是装饰后,名称 add 指向的是 wrapper 函数对象。

原始函数的名称和文档字符串并不会自动转移到包装函数上。

5.1 使用 wraps 保留元信息

Python 标准库 functools 提供了 wraps 装饰器。

from functools import wraps


def decorator(func):

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

    return wrapper


@decorator
def add(a, b):
    """计算两个数的和"""
    return a + b


print(add.__name__)
print(add.__doc__)

输出:

add
计算两个数的和

@wraps(func) 本质上是对包装函数执行元信息复制,并设置 __wrapped__ 属性。

常见保留信息包括:

  • __name__:函数名称。
  • __doc__:文档字符串。
  • __module__:所属模块。
  • __annotations__:类型注解。
  • __qualname__:限定名称。
  • __wrapped__:指向被包装的原始函数。

5.2 wraps 不会改变包装函数的真实参数绑定规则

需要特别注意:functools.wraps 不会自动把包装函数的真实参数列表改成原始函数的参数列表。

例如:

from functools import wraps
import inspect


def decorator(func):

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

    return wrapper


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


print(inspect.signature(add))

输出:

(a, b)

这里 inspect.signature() 默认会沿着 __wrapped__ 属性追踪原始函数,因此显示原始函数的签名。

但包装函数实际定义的参数仍然是:

(*args, **kwargs)

这是元信息展示与实际参数绑定行为之间的区别。

六、带参数的装饰器

前面介绍的装饰器直接接收被装饰函数。

有时我们还希望装饰器本身能够接收配置参数,例如:

  • 设置日志级别。
  • 指定重试次数。
  • 控制缓存容量。
  • 设置访问权限。
  • 配置执行超时时间。

这就需要带参数的装饰器。

6.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

这里存在三层函数:

函数 作用
decorator_with_args 接收装饰器配置参数
decorator 接收被装饰函数
wrapper 执行增强逻辑并调用原函数

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

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

等价于:

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


hello = decorator_with_args("INFO")(hello)

执行过程:

  1. 调用 decorator_with_args("INFO")。
  2. 返回真正的装饰器 decorator。
  3. 将原始函数 hello 传给 decorator。
  4. 创建并返回包装函数 wrapper。
  5. 将名称 hello 绑定到包装函数。

6.3 带参数装饰器的流程

flowchart TD
    A["提供装饰器配置参数"] --> B["调用外层配置函数"]
    B --> C["返回内部装饰器"]
    C --> D["传入原始函数"]
    D --> E["创建包装函数"]
    E --> F["返回包装函数"]
    F --> G["函数名称重新绑定"]
    G --> H["调用包装函数"]
    H --> I["读取配置并执行增强逻辑"]
    I --> J["调用原始函数"]
    style A fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style H fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style I fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style J fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

七、多个装饰器的执行顺序

Python 允许一个函数同时使用多个装饰器。

例如:

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 结束

7.1 装饰器的应用顺序

多个装饰器:

@decorator_a
@decorator_b
def hello():
    pass

等价于:

hello = decorator_a(decorator_b(hello))

因此:

  • 装饰器应用顺序:从下到上。
  • 包装函数进入顺序:从上到下。
  • 包装函数退出顺序:从下到上。

可以理解为多层包装结构: