Python 3.2+functoolsfunction
functools.lru_cache
functools
Decorator caching a function's results by arguments (LRU-bounded by maxsize).
Syntax
@functools.lru_cache(maxsize=128)
The cache key is built from the arguments themselves, so f(2) and f(n=2) occupy different slots, and passing a list or dict raises TypeError: unhashable straight away. There is one cache per function and it lives for the whole program: applied to a method it pins self and blocks garbage collection — clear it with f.cache_clear(). For recursion the default maxsize=128 is often too small, while maxsize=None (exactly what functools.cache does) also drops the eviction overhead.
Examples
import functools
@functools.lru_cache
def sq(n):
return n * n
print(sq(4)) # → 16
print(sq(4), sq.cache_info().hits) # → 16 1
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy