Python Decorator Pattern
The core idea of the Decorator pattern is wrapping - by creating a wrapper object (decorator) to wrap the original object, its functionality is extended without modifying the original object.
Basic concepts
The Decorator pattern contains four main roles:
- Component interface (Component): defines the common interface shared by decorated objects and decorators
- Concrete component (Concrete Component): the original object to be decorated
- Decorator base class (Decorator): holds a reference to a component object and implements the component interface
- Concrete decorator (Concrete Decorator): implements the specific decoration functionality

Basic syntax of decorators
Function decorators
A function decorator is the most common form of decorator; it takes a function as an argument and returns a new function.
Example
def
my_decorator
(
func
)
:
def
wrapper
(
*args
,
**kwargs
)
:
(
"Some operations before the function executes"
)
result
=
func
(
*args
,
**kwargs
)
(
"Some operations after the function executes"
)
return
result
return
wrapper
@
my_decorator
def
say_hello
(
name
)
:
(
f
"Hello, {name}!"
)
Using decorators
say_hello
(
"Alice"
)
Output result:
函数执行前的一些操作
Hello, Alice!
函数执行后的一些操作
Decorators with parameters
If you need to pass arguments to the decorator, you need to nest one more level of function:
Example
def
repeat
(
times
)
:
def
decorator
(
func
)
:
def
wrapper
(
*args
,
**kwargs
)
:
for
i
in
range
(
times
)
:
(
f
"Execution {i+1}:"
)
result
=
func
(
*args
,
**kwargs
)
return
result
return
wrapper
return
decorator
@
repeat
(
times
=
3
)
def
greet
(
name
)
:
(
f
"Hello, {name}!"
)
greet
(
"Bob"
)
Class decorators
Besides function decorators, Python also supports class decorators. Class decorators work by implementing __call__ methods.
Basic class decorators
Example
class
TimerDecorator:
def
init
(
self
,
func
)
:
self
.
func
=
func
def
call
(
self
,
*args
,
**kwargs
)
:
import
time
start_time
=
time
.
time
(
)
result
=
self
.
func
(
*args
,
**kwargs
)
end_time
=
time
.
time
(
)
(
f
"Function {self.func.name} execution took: {end_time - start_time:.4f} seconds"
)
return
result
@
TimerDecorator
def
calculate_sum
(
n
)
:
return
sum
(
range
(
n
)
)
result
=
calculate_sum
(
1000000
)
(
f
"Calculation result: {result}"
)
Class decorators with parameters
Example
class
LogDecorator:
def
init
(
self
,
level
=
"INFO"
)
:
self
.
level
=
level
def
call
(
self
,
func
)
:
def
wrapper
(
*args
,
**kwargs
)
:
(
f
"[{self.level}] Calling function: {func.name}"
)
(
f
"[{self.level}] Arguments: args={args}, kwargs={kwargs}"
)
result
=
func
(
*args
,
**kwargs
)
(
f
"[{self.level}] Return value: {result}"
)
return
result
return
wrapper
@
LogDecorator
(
level
=
"DEBUG"
)
def
multiply
(
a
,
b
)
:
return
a * b
multiply
(
5
,
3
)
Built-in decorators
Python provides some useful built-in decorators:
@staticmethod and @classmethod
Example
class
Calculator:
@
staticmethod
def
add
(
x
,
y
)
:
return
x + y
@
classmethod
def
multiply
(
cls
,
x
,
y
)
:
return
x * y
Using static methods
result1
=
Calculator.
add
(
5
,
3
)
(
f
"Static method result: {result1}"
)
Using class methods
result2
=
Calculator.
multiply
(
5
,
3
)
(
f
"Class method result: {result2}"
)
@property
Example
class
Circle:
def
init
(
self
,
radius
)
:
self
._radius
=
radius
@
property
def
radius
(
self
)
:
return
self
._radius
@
radius.
setter
def
radius
(
self
,
value
)
:
if
value
<=
0
:
raise
ValueError
(
"Radius must be a positive number"
)
self
._radius
=
value
@
property
def
area
(
self
)
:
return
3.14159
self
._radius **
2
circle
=
Circle
(
5
)
(
f
"Radius: {circle.radius}"
)
(
f
"Area: {circle.area}"
)
circle.
radius
=
10
(
f
"New radius: {circle.radius}"
)
(
f
"New area: {circle.area}"
)
Practical application scenarios of decorators
1. Logging
Example
def
log_execution
(
func
)
:
def
wrapper
(
*args
,
**kwargs
)
:
(
f
"Start executing: {func.name}"
)
try
:
result
=
func
(
*args
,
**kwargs
)
(
f
"Completed successfully: {func.name}"
)
return
result
except
Exception
as
e:
(
f
"Execution failed: {func.name}, error: {e}"
)
raise
return
wrapper
@
log_execution
def
process_data
(
data
)
:
Simulate data processing
if
not
data:
raise
ValueError
(
"Data cannot be empty"
)
return
[
x *
2
for
x
in
data
]
Testing
data
=
[
1
,
2
,
3
]
result
=
process_data
(
data
)
(
f
"Processing result: {result}"
)
2. Permission verification
Example
def
require_login
(
func
)
:
def
wrapper
(
user
,
*args
,
**kwargs
)
:
if
not
user
.
get
(
'is_authenticated'
,
False
)
:
raise
PermissionError
(
"User not logged in"
)
return
func
(
user
,
*args
,
**kwargs
)
return
wrapper
@
require_login
def
view_profile
(
user
)
:
return
f
"Viewing the profile of user {user['username']}"
Testing
user1
=
{
'username'
:
'alice'
,
'is_authenticated'
:
True
}
user2
=
{
'username'
:
'bob'
,
'is_authenticated'
:
False
}
(
view_profile
(
user1
)
)
Normal execution
print(view_profile(user2)) # will raise PermissionError
3. Caching decorator
Example
def
cache_results
(
func
)
:
cache
=
{
}
def
wrapper
(
*args
)
:
if
args
in
cache:
(
f
"Fetching result from cache: {args}"
)
return
cache
[
args
]
result
=
func
(
*args
)
cache
[
args
]
=
result
(
f
"Computing and caching result: {args} -> {result}"
)
return
result
return
wrapper
@
cache_results
def
fibonacci
(
n
)
:
if
n
<=
1
:
return
n
return
fibonacci
(
n-
1
)
- fibonacci
(
n-
2
)
Test the caching effect
(
fibonacci
(
5
)
)
(
fibonacci
(
5
)
)
This time it will be fetched from the cache
Execution order of multiple decorators
When using multiple decorators, their execution order is from bottom to top:
Example
def
decorator1
(
func
)
:
def
wrapper
(
)
:
(
"Decorator 1 - before"
)
func
(
)
(
"Decorator 1 - after"
)
return
wrapper
def
decorator2
(
func
)
:
def
wrapper
(
)
:
(
"Decorator 2 - before"
)
func
(
)
(
"Decorator 2 - after"
)
return
wrapper
@
decorator1
@
decorator2
def
my_function
(
)
:
(
"Original function"
)
my_function
(
)
Output result:
装饰器1 - 前
装饰器2 - 前
原始函数
装饰器2 - 后
装饰器1 - 后
Preserving function metadata
When using decorators, the original function's metadata (such as the function name and docstring) is overwritten by the wrapper function. You can use functools.wraps to preserve this information:
Example
from
functools
import
wraps
def
preserve_metadata
(
func
)
:
@
wraps
(
func
)
def
wrapper
(
*args
,
**kwargs
)
:
"""Docstring of the wrapper function"""
return
func
(
*args
,
**kwargs
)
return
wrapper
@
preserve_metadata
def
example_function
(
)
:
"""This is the docstring of the original function"""
pass
(
f
"Function name: {example_function.name}"
)
(
f
"Docstring: {example_function.doc}"
)
Practical Exercise
Exercise 1: Create a performance monitoring decorator
Write a decorator that monitors a function's execution time and memory usage.
Example
import
time
import
tracemalloc
def
performance_monitor
(
func
)
:
@
wraps
(
func
)
def
wrapper
(
*args
,
**kwargs
)
:
Start memory tracing
tracemalloc.
start
(
)
Record the start time
start_time
=
time
.
time
(
)
Execute the function
result
=
func
(
*args
,
**kwargs
)
Record the end time
end_time
=
time
.
time
(
)
Get memory usage
current
,
peak
=
tracemalloc.
get_traced_memory
(
)
tracemalloc.
stop
(
)
(
f
"Function {func.name} Performance report:"
)
(
f
"Execution time: {end_time - start_time:.4f} seconds"
)
(
f
"Memory usage: current {current/1024:.2f} KB, peak {peak/1024:.2f} KB"
)
return
result
return
wrapper
@
performance_monitor
def
process_large_data
(
)
:
"""Simulate processing a large amount of data"""
data
=
[
i**
2
for
i
in
range
(
100000
)
]
return
sum
(
data
)
process_large_data
(
)
Exercise 2: Implement a retry mechanism decorator
Create a decorator that automatically retries a specified number of times when a function fails.
Example
def
retry
(
max_attempts
=
3
,
delay
=
1
)
:
def
decorator
(
func
)
:
@
wraps
(
func
)
def
wrapper
(
*args
,
**kwargs
)
:
attempts
=
0
while
attempts
<
max_attempts:
try
:
return
func
(
*args
,
**kwargs
)
except
Exception
as
e:
attempts +
=
1
if
attempts
==
max_attempts:
(
f
"Function {func.name} execution failed, maximum retry count reached"
)
raise
(
f
"Function {func.name} attempt {attempts} failed: {e}"
)
(
f
"Waiting {delay} seconds before retrying..."
)
time
.
sleep
(
delay
)
return
None
return
wrapper
return
decorator
@
retry
(
max_attempts
=
3
,
delay
=
2
)
def
unstable_operation
(
)
:
"""Simulate an unstable operation"""
import
random
if
random
.
random
(
)
<
0.7
:
70% chance of failure
raise
ValueError
(
"Random failure"
)
return
"Operation succeeded"
Test the retry mechanism
result
=
unstable_operation
(
)
(
f
"Final result: {result}"
)
Summary
Python decorators are a powerful and flexible tool that offers the following advantages:
- Code Reuse: separating cross-cutting concerns (such as logging, caching, and validation) from business logic
- Dynamic Scaling: adding new functionality without modifying the original code
- Keep it concise: When using
@syntax makes the code clearer and easier to read - Follows the Open/Closed Principle: open for extension, closed for modification
Best practices for using decorators:
- Use
functools.wrapsPreserving function metadata - Keep a decorator's single responsibility
- Handle exceptions in decorators properly
- Pay attention to the execution order of decorators