functools模块通过提供lru_cache、partial和wraps等工具显著提升python代码效率与质量。1. lru_cache通过缓存函数结果避免重复计算,尤其适用于参数不变的高耗时函数,如远程数据获取或递归算法,能大幅提升性能,但要求参数可哈希且需注意内存占用;2. partial通过固定函数部分参数生成新函数,实现逻辑复用与调用简化,相比lambda更具可读性和可维护性,适用于创建专用函数变体或与高阶函数结合使用;3. wraps用于装饰自定义装饰器中的包装函数,确保被装饰函数的__name__、__doc__等元数据得以保留,避免调试困难和工具失效,是编写健壮装饰器的必要步骤。
functools
functools
lru_cache
partial
wraps
lru_cache
lru_cache
functools
立即学习“Python免费学习笔记(深入)”;
lru_cache
@lru_cache()
我个人觉得,很多时候我们写一些服务端的接口,如果底层数据源不经常变动,或者某些查询条件重复率很高,
lru_cache
lru_cache
import time from functools import lru_cache # 模拟一个耗时操作,比如网络请求或复杂计算 @lru_cache(maxsize=None) # maxsize=None 意味着缓存大小无限制,但通常建议设置一个上限 def fetch_data_from_remote(item_id: str) -> str: print(f"正在从远程获取数据 for {item_id}...") time.sleep(2) # 模拟网络延迟 return f"数据 for {item_id} 已获取" print(fetch_data_from_remote("user_profile_1")) # 第一次调用,会等待2秒 print(fetch_data_from_remote("user_profile_2")) # 第一次调用,会等待2秒 print(fetch_data_from_remote("user_profile_1")) # 第二次调用,直接从缓存返回,几乎瞬时 print(fetch_data_from_remote("user_profile_2")) # 第二次调用,直接从缓存返回,几乎瞬时 # 斐波那契数列的经典优化 @lru_cache(maxsize=128) def fibonacci(n): if n <= 1: return n return fibonacci(n - 1) + fibonacci(n - 2) print("\n计算斐波那契数列:") print([fibonacci(n) for n in range(10)]) # 效率很高,因为重复计算被缓存了
partial
functools.partial
举个例子,你可能有一个通用的
send_notification(message, type, recipient)
send_notification("你好", "email", "user@example.com")
partial
send_email_notification
send_sms_notification
刚开始接触
partial
lambda
partial
partial
__name__
__doc__
lambda
from functools import partial def power(base, exponent): """计算 base 的 exponent 次幂。""" return base ** exponent # 创建一个专门计算平方的函数 square = partial(power, exponent=2) print(f"5 的平方是: {square(5)}") print(f"10 的平方是: {square(10)}") # 创建一个专门计算立方的函数 cube = partial(power, exponent=3) print(f"5 的立方是: {cube(5)}") # 另一个例子:日志记录 def log_message(level, message): """记录带有指定级别的消息。""" print(f"[{level.upper()}]: {message}") # 创建特定级别的日志函数 log_info = partial(log_message, level="info") log_warning = partial(log_message, level="warning") log_error = partial(log_message, level="error") log_info("用户登录成功") log_warning("磁盘空间不足") log_error("数据库连接失败") # 结合高阶函数使用 numbers = [1, 2, 3, 4, 5] # 过滤出大于等于3的数字 is_greater_than_or_equal_to_3 = partial(lambda x, threshold: x >= threshold, threshold=3) filtered_numbers = list(filter(is_greater_than_or_equal_to_3, numbers)) print(f"大于等于3的数字: {filtered_numbers}")
wraps
如果你写过 Python 装饰器,并且在调试或者查看被装饰函数的信息时遇到过困惑,那么
functools.wraps
这意味着什么呢?当你调试一个被装饰的函数时,它的
__name__
__doc__
functools.wraps
wraps
__name__
__doc__
__module__
__annotations__
我记得有一次调试一个复杂的系统,好几个装饰器套在一起,结果断点打进去一看,函数名和文档字符串全乱了,简直是噩梦。后来才发现
functools.wraps
from functools import wraps # 错误的装饰器实现,会丢失被装饰函数的元数据 def my_bad_decorator(func): def wrapper(*args, **kwargs): print("Something is happening before the function is called.") result = func(*args, **kwargs) print("Something is happening after the function is called.") return result return wrapper @my_bad_decorator def say_hello_bad(name): """一个简单的问候函数.""" return f"Hello, {name}!" print("--- 错误装饰器示例 ---") print(f"函数名: {say_hello_bad.__name__}") # 打印 'wrapper' print(f"文档字符串: {say_hello_bad.__doc__}") # 打印 None say_hello_bad("Alice") # 正确的装饰器实现,使用 @wraps 保持元数据 def my_good_decorator(func): @wraps(func) # 关键在这里! def wrapper(*args, **kwargs): print("Something good is happening before the function is called.") result = func(*args, **kwargs) print("Something good is happening after the function is called.") return result return wrapper @my_good_decorator def say_hello_good(name): """一个更好的问候函数.""" return f"Hello, {name}!" print("\n--- 正确装饰器示例 ---") print(f"函数名: {say_hello_good.__name__}") # 打印 'say_hello_good' print(f"文档字符串: {say_hello_good.__doc__}") # 打印 '一个更好的问候函数.' say_hello_good("Bob")
以上就是Python函数如何用 functools 模块优化函数 Python函数 functools 工具的基础应用技巧的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号