Python深度解析:装饰器—提升代码灵活性与可维护性的艺术
在Python编程中,装饰器是一种功能强大且优雅的工具,能够在不改变函数定义的前提下,动态地扩展或修改其行为。使用装饰器不仅能够提升代码的可读性和可重用性,还能在实际开发中实现更高效的解决方案。
装饰器的基本概念
定义与语法
装饰器本质上是一个高阶函数,它接收一个函数作为输入,并返回一个新的函数。通过在函数定义前添加@decorator_name语法,Python会在函数调用时首先执行装饰器逻辑,再调用函数本身。通过@decorator_name语法实际效果是和decorator_name(func) 是一样的,可以参考下面的例子
def simple_decorator(func):
def wrapper(*args, **kwargs):
print("Before function call")
result = func(*args, **kwargs)
print("After function call")
return result
return wrapper
@simple_decorator
def say_hello(name):
print(f"Hello, {name}!")
say_hello("Alice")
# Before function call
# Hello, Alice!
# After function call
simple_decorator(say_hello("Alice"))
# Before function call
# Hello, Alice!
# After function call
工作原理
装饰器的核心是函数包装,通过在wrapper函数中添加额外的逻辑,我们可以在函数执行前后插入自定义行为,这在日志记录、性能监控、权限验证等场景中非常有用。
编写自定义装饰器
编写一个自定义装饰器通常包括以下步骤:
- 定义一个接收函数作为参数的装饰器函数。
- 在装饰器函数内部定义一个包装函数,处理传入的参数和返回值。
- 在包装函数内编写所需的附加逻辑。
- 返回包装函数,使其替代原始函数。
以下示例展示了一个用于记录函数执行时间的装饰器:
import time
from functools import wraps
def timing_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"{func.__name__} executed in {end_time - start_time:.4f} seconds")
return result
return wrapper
@timing_decorator
def compute_square(n):
return n * n
compute_square(4)
functools.wraps 的使用
在记录函数执行时间的例子里面,使用到了functools.wraps。它的作用是保留原始函数的元数据,比如 __name__ 和 __doc__ 的属性,我们可以看下面这个例子
from functools import wraps
def simple_decorator(func):
def wrapper(*args, **kwargs):
print("Before function call")
result = func(*args, **kwargs)
print("After function call")
return result
return wrapper
def simple_decorator_with_wraps(func):
@wraps(func)
def wrapper(*args, **kwargs):
print("Before function call")
result = func(*args, **kwargs)
print("After function call")
return result
return wrapper
@simple_decorator
def my_function():
"""This is my_function."""
print("Executing my_function")
@simple_decorator_with_wraps
def my_function2():
"""This is my_function2."""
print("Executing my_function")
print(my_function.__name__) # 输出:wrapper
print(my_function.__doc__) # 输出:None
print(my_function2.__name__) # 输出:my_function2
print(my_function2.__doc__) # 输出:This is my_function2.
实际应用案例
装饰器在实际开发中的应用非常广泛。以下是几个典型场景:
- 日志记录:自动记录函数的调用信息。
- 性能测试:衡量函数的执行时间。
- 事务处理:在数据库操作中确保事务的开始和提交。
- 访问控制:在函数调用前进行权限验证。
这些应用不仅提高了代码的可维护性,也使得业务逻辑与辅助功能之间的耦合更低。
注意事项与常见问题
在使用装饰器时,可能会遇到以下问题:
- 闭包的使用:装饰器的包装函数通常是闭包,正确处理闭包变量非常重要。
- 装饰器顺序:当多个装饰器同时应用时,它们的执行顺序会影响最终结果。
- 调试困难:装饰器会修改函数的行为,可能导致调试难度增加。使用
functools.wraps可以帮助保留原函数的信息。
面试常见问题
实现一个记录函数的调用时间、参数、返回值日志的装饰器
import time
import logging
from functools import wraps
# 设置日志记录
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def log_execution(func):
@wraps(func)
def wrapper(*args, **kwargs):
# 记录函数开始执行时间
start_time = time.time()
# 记录函数参数
logging.info(f"Calling {func.__name__} with args: {args} and kwargs: {kwargs}")
# 执行函数
result = func(*args, **kwargs)
# 记录函数结束时间和执行时间
end_time = time.time()
execution_time = end_time - start_time
# 记录返回值和执行时间
logging.info(f"{func.__name__} returned {result} in {execution_time:.4f} seconds")
return result
return wrapper
# 示例函数
@log_execution
def example_function(a, b, delay=1):
time.sleep(delay)
return a + b
# 调用示例函数
example_function(5, 10, delay=2)
实现一个记录函数的执行时间的装饰器
import time
from functools import wraps
def timing_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
# 记录开始时间
start_time = time.time()
# 执行函数
result = func(*args, **kwargs)
# 记录结束时间
end_time = time.time()
# 计算并打印执行时间
execution_time = end_time - start_time
print(f"{func.__name__} executed in {execution_time:.4f} seconds")
return result
return wrapper
# 示例函数
@timing_decorator
def example_function(a, b):
time.sleep(1) # 模拟耗时操作
return a + b
# 调用示例函数
result = example_function(5, 10)
定义一个带参数的装饰器
from functools import wraps
def repeat_decorator(times):
"""一个装饰器,它会重复执行被装饰的函数指定的次数"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
result = None
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
# 示例函数
@repeat_decorator(times=3)
def greet(name):
print(f"Hello, {name}!")
# 调用示例函数
greet("Alice")
实现一个失败重试的装饰器
import time
from functools import wraps
def retry_decorator(max_retries=3, delay=1, exceptions=(Exception,)):
"""
一个失败重试的装饰器。
:param max_retries: 最大重试次数
:param delay: 每次重试之间的延迟时间(秒)
:param exceptions: 触发重试的异常类型元组
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
attempts = 0
while attempts < max_retries:
try:
return func(*args, **kwargs)
except exceptions as e:
attempts += 1
print(f"Attempt {attempts} failed: {e}")
if attempts < max_retries:
time.sleep(delay)
else:
print(f"All {max_retries} attempts failed.")
raise
return wrapper
return decorator
# 示例函数
@retry_decorator(max_retries=5, delay=2)
def unstable_function():
# 模拟可能失败的操作
if time.time() % 2 < 1: # 模拟50%的概率失败
raise ValueError("Simulated failure")
return "Success!"
# 调用示例函数
try:
result = unstable_function()
print(result)
except Exception as e:
print(f"Function failed after all retries: {e}")
实现一个用于参数校验的装饰器
from functools import wraps
def validate_params(**validators):
"""
参数校验装饰器。
:param validators: 一个字典,键是参数名,值是校验函数或校验规则的元组。
校验函数接收参数值并返回True或False,表示参数是否合法。
校验规则元组可以包含预期的类型和一个可选的范围检查函数。
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
# 获取函数的参数名列表
func_args = func.__code__.co_varnames
# 对位置参数进行校验
for i, arg in enumerate(args):
if i < len(func_args):
param_name = func_args[i]
if param_name in validators:
validate(arg, validators[param_name], param_name)
# 对关键字参数进行校验
for param_name, arg in kwargs.items():
if param_name in validators:
validate(arg, validators[param_name], param_name)
return func(*args, **kwargs)
return wrapper
return decorator
def validate(value, validator, param_name):
"""通用的验证函数,用于验证参数是否满足条件"""
if isinstance(validator, tuple):
expected_type = validator[0]
range_check = validator[1] if len(validator) > 1 else lambda x: True
if not isinstance(value, expected_type):
raise TypeError(f"Parameter '{param_name}' must be of type {expected_type.__name__}")
if not range_check(value):
raise ValueError(f"Parameter '{param_name}' failed the range check.")
elif callable(validator):
if not validator(value):
raise ValueError(f"Parameter '{param_name}' failed custom validation.")
# 示例函数
@validate_params(
x=(int, lambda v: v > 0), # x 必须是正整数
y=(float, lambda v: 0.0 <= v <= 1.0), # y 必须是0到1之间的浮点数
name=str # name 必须是字符串
)
def process_data(x, y, name="default"):
print(f"Processing data: x={x}, y={y}, name={name}")
# 调用示例函数
try:
process_data(10, 0.5, name="example")
process_data(-1, 0.5, name="example") # 这将引发TypeError
except Exception as e:
print(f"Validation error: {e}")
实现一个限制函数调用次数限制的装饰器
from functools import wraps
def limit_calls(max_calls, on_limit_reached=None):
"""
限制函数调用次数的装饰器。
:param max_calls: 最大允许调用次数
:param on_limit_reached: 当超过调用限制时执行的操作,可以是一个函数,也可以是一个值
"""
def decorator(func):
calls = 0 # 内部计数器
@wraps(func)
def wrapper(*args, **kwargs):
nonlocal calls # 这里使用闭包去处理计数器,可以根据实际使用情况调整
if calls >= max_calls:
if callable(on_limit_reached):
return on_limit_reached(*args, **kwargs)
else:
return on_limit_reached
calls += 1
return func(*args, **kwargs)
return wrapper
return decorator
# 示例函数
@limit_calls(max_calls=3, on_limit_reached="Function call limit reached")
def example_function(x, y):
return x + y
# 调用示例函数
print(example_function(1, 2)) # 1st call
print(example_function(3, 4)) # 2nd call
print(example_function(5, 6)) # 3rd call
print(example_function(7, 8)) # 4th call - exceeds limit
提供一个函数,在不改变原有的函数的情况下,增加一个参数
from functools import wraps
def add_parameter(new_param_name, new_param_value):
"""
装饰器,用于在不改变原有函数的情况下增加一个新的参数。
:param new_param_name: 新参数的名称
:param new_param_value: 新参数的默认值
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
# 添加新参数到kwargs
kwargs[new_param_name] = new_param_value
return func(*args, **kwargs)
return wrapper
return decorator
# 示例函数
def original_function(x, y):
print(f"x = {x}, y = {y}")
# 使用装饰器添加新参数
@add_parameter('z', 10)
def modified_function(x, y, **kwargs):
print(f"x = {x}, y = {y}, z = {kwargs.get('z')}")
# 调用示例函数
modified_function(1, 2)
备注: 本文会同步发布于个人微信公众号(smith日常碎碎念)。