开袋即食
functools 把「高阶函数」打包成 3 个即插即用的 API:
@lru_cache 自动记忆、@wraps 装饰器美颜、partial 预设参数,一行顶十行。
1 行代码 3 连发
from functools import lru_cache, wraps, partial
@lru_cache(maxsize=None) # 无限缓存
def fib(n): return n if n < 2 else fib(n-1) + fib(n-2)
@wraps(func) # 保留原函数签名
def wrapper(*a, **kw): return func(*a, **kw)
int16 = partial(int, base=16) # 预设进制
场景实拍:接口缓存 30 秒,减少 90 % 重复请求
需求:天气 API 调用费钱,30 秒内同一城市直接返回缓存。
import requests, time
from functools import lru_cache
@lru_cache(maxsize=128, typed=False)
def weather(city: str) -> dict:
print(f"💸 真实请求 {city}")
url = f"https://api.openweathermap.org/data/2.5/weather"
return requests.get(url, params={"q": city, "appid": "xxx"}).json()
# 30 秒后缓存自动失效
weather("London")
time.sleep(1)
weather("London") # 直接走缓存,无打印
升级加料
cache_clear()手动清空缓存。@singledispatch做函数重载。partialmethod给类方法预设参数。
打包带走 :
函数重复算?@lru_cache 贴上!
参数太长?partial 预设!
装饰器丢签名?@wraps 美颜!
1111

被折叠的 条评论
为什么被折叠?



