有些小函数会被反复调用,参数又总是一样。先丢个 cache,代码能干净不少。
环境:Python 3.9+,只用标准库。
from functools import cache
@cache
def slow_square(n: int) -> int:
print('算一次:', n)
return n * n
print(slow_square(4))
print(slow_square(4))
第二次同样的参数就直接拿结果了,不用自己手搓字典。要是还想限制缓存大小,再换 lru_cache 就行。