functool 的缓存与 lru_cache 的区别

Difference between functool's cache and lru_cache

最近我遇到了functools.cache and didn't know how it differs from functools.lru_cache

我找到了 posts about the difference between functools.cached_propertylru_cache,但没有找到 cachelru_cache

functools.cache是3.9版本新增的

文档指出:

Simple lightweight unbounded function cache. Sometimes called “memoize”.

Returns the same as lru_cache(maxsize=None), creating a thin wrapper around a dictionary lookup for the function arguments. Because it never needs to evict old values, this is smaller and faster than lru_cache() with a size limit.

文档中的示例:

@cache
def factorial(n):
    return n * factorial(n-1) if n else 1

>>> factorial(10)      # no previously cached result, makes 11 recursive calls
3628800
>>> factorial(5)       # just looks up cached value result
120
>>> factorial(12)      # makes two new recursive calls, the other 10 are cached
479001600

所以,简而言之:cachelru_cache(maxsize=None) 完全相同(link 到 cpython 源)。但是在您不想限制缓存大小的情况下,使用 cache 可能会使代码更清晰,因为没有限制的最近最少使用的缓存没有多大意义。