1. What Is a Decorator
A decorator is a mechanism for extending the behavior of a function or class. It typically takes a callable object as an argument, processes it, and returns another callable object.
The core idea of a decorator is: do not directly modify the original function; instead, add a layer of wrapper logic around it.
For example:
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()
Output:
Function starts executing
Hello Python
Function execution ends
In this code:
say_hellois the original function.log_decoratortakes the original function as an argument.wrapperis the wrapper function responsible for enhancing behavior.wrappercalls the original function during execution.log_decoratorreturns the wrapper function.say_helloultimately points to the wrapper function.
The business logic of the original function remains unchanged, but extra behavior is added when it is called.
1.1 The Essence of Decorators
Essentially, a decorator is a higher-order function.
A higher-order function satisfies either of the following conditions:
- It takes a function or another callable object as an argument.
- It returns a function or another callable object.
Decorators usually satisfy both conditions at the same time:
def decorator(func):
def wrapper():
return func()
return wrapper
Here:
decoratortakes a function object.wrapperis the inner function.wrapperreferences the outer variablefunc, forming a closure.decoratorreturns thewrapperfunction object.
Therefore, the function decorators commonly seen in Python actually combine mechanisms such as higher-order functions, closures, and function objects.
2. Basic Syntax of Decorators
Python provides the @ syntactic sugar to simplify the application of decorators.
For example:
def log_decorator(func):
def wrapper():
print("函数开始执行")
func()
print("函数执行结束")
return wrapper
@log_decorator
def say_hello():
print("Hello Python")
say_hello()
Output:
Function starts executing
Hello Python
Function execution ends
Here:
@log_decorator
def say_hello():
print("Hello Python")
is equivalent to:
def say_hello():
print("Hello Python")
say_hello = log_decorator(say_hello)
In other words, @decorator is not a special way of defining functions; it is the syntax Python provides for applying decorators.
2.1 When Decorators Execute
There is an important difference between decorators and ordinary function calls: a decorator expression usually executes during the function definition stage, not every time the function is called.
def decorator(func):
print("装饰器开始执行")
def wrapper():
print("包装函数执行")
return func()
return wrapper
@decorator
def hello():
print("Hello")
print("程序继续执行")
hello()
hello()
Output:
Decorator starts executing
Program continues executing
Wrapper function executes
Hello
Wrapper function executes
Hello
You can observe that:
- When
hellois defined, the decorator executes once. - The decorator returns the wrapper function.
- Each time
hello()is called, the wrapper function is executed. - The wrapper function then calls the original function internally.
Therefore, when the decorator is applied and when the wrapper function is called are two different stages.
2.2 Decorator Execution Flow
flowchart TD
A["Interpreter executes function definition"] --> B["Create original function object"]
B --> C["Call decorator"]
C --> D["Pass in original function object"]
D --> E["Create wrapper function"]
E --> F["Return wrapper function"]
F --> G["Rebind function name"]
G --> H["Subsequent calls invoke wrapper function"]
H --> I["Execute enhanced logic"]
I --> J["Call original function"]
J --> K["Return execution result"]
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
3. Underlying Implementation Principles of Decorators
To understand decorators, you first need to grasp several fundamental mechanisms in Python.
3.1 Functions Are First-Class Objects
In Python, functions themselves are objects.
Functions can:
- Be assigned to variables.
- Be passed as arguments.
- Be returned as function return values.
- Be stored in containers such as lists and dictionaries.
- Be created and replaced dynamically at runtime.
For example:
def greet():
return "Hello"
another_greet = greet
print(another_greet())
print(greet is another_greet)
Output:
Hello
True
another_greet and greet refer to the same function object.
Decorators are implemented precisely by taking advantage of the fact that functions can be used as arguments and return values.
3.2 Closures Retain the Original Function
The wrapper function in a decorator usually needs to call the original function.
def decorator(func):
def wrapper():
print("执行前")
result = func()
print("执行后")
return result
return wrapper
Here, func is defined inside decorator(), yet it is used by the inner function wrapper().
Therefore, func is a free variable for wrapper().
After decorator() returns wrapper, the closure mechanism allows the wrapper function to still access the original function object.
This means that even after the decorator function has finished executing, the wrapper function can still call the original function.
3.3 Name Rebinding
Consider the following code:
def decorator(func):
def wrapper():
print("Before")
return func()
return wrapper
def hello():
print("Hello")
hello = decorator(hello)
When the last line is executed:
- Python passes the original
hellofunction object intodecorator. decoratorcreateswrapper.wrapperretains a reference to the originalhellothrough the closure.decoratorreturnswrapper.- The name
hellois rebound to the wrapper function.
Therefore, subsequent call:
hello()
actually executes wrapper().
This can be understood through the following relationship:
flowchart TD
A["Original function hello"] --> B["Passed to decorator"]
B --> C["Wrapper function wrapper"]
C --> D["Closure references original function"]
C --> E["Return wrapper"]
E --> F["hello is rebound"]
F --> G["Call hello"]
G --> H["Actually executes wrapper"]
H --> I["Call original 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
IV. Writing a Generic Decorator
The previous decorators can only handle functions without parameters.
In real-world applications, functions may receive positional arguments and keyword arguments, and may also return different types of data.
Therefore, generic decorators usually use *args and **kwargs.
4.1 Support Arbitrary Arguments
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"))
Output:
调用函数:add
30
调用函数:greet
Hello, Python
Here:
*argsreceives any number of positional arguments.**kwargsreceives any number of keyword arguments.func(*args, **kwargs)passes the arguments back to the original function.
This way, the decorator does not need to know the parameter structure of the original function in advance.
4.2 Preserve the Original Function's Return Value
The wrapper function should correctly return the execution result of the original function.
Not recommended:
def decorator(func):
def wrapper(*args, **kwargs):
func(*args, **kwargs)
return wrapper
This approach discards the return value of the original function.
Recommended:
def decorator(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result
return wrapper
It can also be simplified to:
def decorator(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
For generic decorators, preserving the return value is a very important design principle.
4.3 Preserve Exception Propagation Behavior
When the wrapper function calls the original function, if the original function raises an exception, the exception should usually continue to propagate to the caller.
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))
Output:
Function starts executing
Function execution ends
5.0
If the divisor is zero, the exception is logged and then re-raised.
Using raise instead of raise exc preserves the propagation semantics of the original exception and provides more complete traceback information.
5. The Role of functools.wraps
After using a decorator, metadata such as the function name and docstring may change.
For example:
def decorator(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@decorator
def add(a, b):
"""Calculate the sum of two numbers"""
return a + b
print(add.__name__)
print(add.__doc__)
Output:
wrapper
None
The reason is that after decoration, the name add points to the wrapper function object.
The original function's name and docstring are not automatically transferred to the wrapper function.
5.1 Using wraps to Preserve Metadata
Python's standard library functools provides the wraps decorator.
from functools import wraps
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@decorator
def add(a, b):
"""Calculate the sum of two numbers"""
return a + b
print(add.__name__)
print(add.__doc__)
Output:
add
Calculate the sum of two numbers
@wraps(func) essentially copies metadata onto the wrapper function and sets the __wrapped__ attribute.
Commonly preserved information includes:
__name__: function name.__doc__: docstring.__module__: module it belongs to.__annotations__: type annotations.__qualname__: qualified name.__wrapped__: points to the original wrapped function.
5.2 wraps Does Not Change the Wrapper Function's Actual Parameter Binding Rules
Pay special attention: functools.wraps does not automatically change the wrapper function's actual parameter list to the original function's parameter list.
For example:
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))
Output:
(a, b)
Here, inspect.signature() by default follows the __wrapped__ attribute to the original function, so it displays the original function's signature.
However, the parameters actually defined by the wrapper function are still:
(*args, **kwargs)
This is the difference between metadata display and actual parameter binding behavior.
6. Decorators with Parameters
The decorators introduced earlier directly receive the function being decorated.
Sometimes we also want the decorator itself to receive configuration parameters, for example:
- Set the log level.
- Specify the number of retries.
- Control cache capacity.
- Set access permissions.
- Configure the execution timeout.
This requires decorators with parameters.
6.1 Basic Structure
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
Here there are three levels of functions:
| Function | Purpose |
|---|---|
decorator_with_args |
Accepts decorator configuration parameters |
decorator |
Receives the decorated function |
wrapper |
Executes enhanced logic and calls the original function |
6.2 Equivalent Form of a Decorator with Parameters
@decorator_with_args("INFO")
def hello():
print("Hello Python")
is equivalent to:
def hello():
print("Hello Python")
hello = decorator_with_args("INFO")(hello)
Execution process:
- Call
decorator_with_args("INFO"). - Return the actual decorator
decorator. - Pass the original function
hellotodecorator. - Create and return the wrapper function
wrapper. - Bind the name
helloto the wrapper function.
6.3 Flow of a Decorator with Parameters
flowchart TD
A["Provide decorator configuration parameters"] --> B["Call outer configuration function"]
B --> C["Return inner decorator"]
C --> D["Pass in original function"]
D --> E["Create wrapper function"]
E --> F["Return wrapper function"]
F --> G["Rebind function name"]
G --> H["Call wrapper function"]
H --> I["Read configuration and execute enhanced logic"]
I --> J["Call original function"]
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
7. Execution Order of Multiple Decorators
Python allows a function to use multiple decorators at the same time.
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 start
B start
Hello Python
B end
A end
7.1 Application Order of Decorators
Multiple decorators:
@decorator_a
@decorator_b
def hello():
pass
is equivalent to:
hello = decorator_a(decorator_b(hello))
Therefore:
- Decorator application order: bottom to top.
- Wrapper function entry order: top to bottom.
- Wrapper function exit order: bottom to top.
It can be understood as a multi-layer wrapping structure: