CKTIS / Python
functools.cache
Memoizes function results in an unbounded cache keyed by call arguments.
Version: Python 3.14; repository image, production runtime not attested
Syntax
@functools.cacheMemoizes function results in an unbounded cache keyed by call arguments.
A repeated call with the same cache key reuses the stored result. An unbounded cache can retain arguments indefinitely.
An unbounded memoizer equivalent to lru_cache(maxsize=None) stores results by a hashable call key. Distinct argument forms, including keyword order, may create separate keys. Arguments and results remain referenced until the cache is cleared or discarded. Concurrent misses can compute a value twice. Both square(4) calls return 16, but calls records only one 4. In CPython, f(1) and f(1.0) produce distinct keys despite 1 == 1.0.
from functools import cache
@cache
def f(x):
return object()
a = f(4)
assert f(4) is a and f.cache_info().hits == 1
f.cache_clear()
assert f(4) is not a
try:
f([])
except TypeError:
pass
else:
raise AssertionError
f.cache_clear()
assert f(1) is not f(1.0) and f.cache_info().misses == 2
Examples
import functools
calls = []
@functools.cache
def square(n):
calls.append(n)
return n * n
print(square(4), square(4), calls)
Result
16 16 [4]
An unbounded memoizer equivalent to lru_cache(maxsize=None) stores results by a hashable call key. Distinct argument forms, including keyword order, may create separate keys. Arguments and results remain referenced until the cache is cleared or discarded. Concurrent misses can compute a value twice. Both square(4) calls return 16, but calls records only one 4. In CPython, f(1) and f(1.0) produce distinct keys despite 1 == 1.0.