本文最后更新于20 天前,其中的信息可能已经过时,如有错误请发送邮件到linmwo@qq.com
functools
是 Python 标准库中用于 函数式编程 的工具集合,提供了高阶函数与装饰器,方便实现缓存、偏函数、比较规则、装饰器开发等功能。
1. functools.partial
—— 偏函数
用于 固定部分参数,生成一个新的函数,减少重复传参。
from functools import partial
def power(base, exp):
return base ** exp
square = partial(power, exp=2)
cube = partial(power, exp=3)
print(square(5)) # 25
print(cube(2)) # 8
使用场景:
- 频繁调用某函数但参数固定。
- GUI 绑定回调函数,传递固定参数。
2. functools.wraps
—— 编写优雅装饰器
装饰器会改变被装饰函数的 __name__
、__doc__
,wraps
可保持原函数信息。
from functools import wraps
def logger(func):
@wraps(func)
def wrapper(*args, **kwargs):
print(f"调用 {func.__name__}()")
return func(*args, **kwargs)
return wrapper
@logger
def greet(name):
"""问候函数"""
print(f"Hello, {name}")
greet("Alice")
print(greet.__name__) # greet
print(greet.__doc__) # 问候函数
3. functools.lru_cache
—— 缓存函数结果
Least Recently Used Cache,提升重复调用的性能。
from functools import lru_cache
import time
@lru_cache(maxsize=128)
def slow_add(a, b):
time.sleep(1)
return a + b
print(slow_add(1, 2)) # 第一次 1s
print(slow_add(1, 2)) # 缓存命中,瞬间返回
注意:缓存依赖 参数可哈希性。
4. functools.reduce
—— 累积运算
对序列做 二元累积操作。
from functools import reduce
nums = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, nums)
print(product) # 24
替代方案:多数情况可用 sum()
、math.prod()
或循环代替,但 reduce
适用于复杂累积逻辑。
5. functools.cmp_to_key
—— 自定义排序
Python 3 移除了 cmp
参数,改用 key
。此函数可将比较函数转换为 key
。
from functools import cmp_to_key
def compare(a, b):
return len(a) - len(b)
words = ["pear", "apple", "banana"]
words.sort(key=cmp_to_key(compare))
print(words) # ['pear', 'apple', 'banana']
6. functools.singledispatch
—— 单分派泛型函数
实现“函数重载”,根据第一个参数类型自动选择实现。
from functools import singledispatch
@singledispatch
def process(data):
print("默认处理:", data)
@process.register
def _(data: int):
print("处理整数:", data)
@process.register
def _(data: list):
print("处理列表:", data)
process(10) # 处理整数
process([1, 2]) # 处理列表
process("abc") # 默认处理
7. 其他实用函数
functools.total_ordering
:简化比较方法的编写,自动补全__lt__
、__eq__
。functools.cache
:Python 3.9+,与lru_cache(maxsize=None)
等效,简单无限缓存。functools.update_wrapper
:装饰器内部保持元信息(wraps
的底层实现)。
8. 学习小结
- 函数式编程:偏函数(
partial
)、累积(reduce
)。 - 性能优化:缓存(
lru_cache
,cache
)。 - 装饰器开发:
wraps
,update_wrapper
。 - 扩展功能:泛型函数(
singledispatch
)、排序(cmp_to_key
)、类比较(total_ordering
)。
functools
提供的这些工具非常适合 提高代码可读性、减少重复、提升性能。
Views: 0