functools.lru_cache, functools.cache
functools.lru_cache(maxsize=128, typed=False)
functools.cache(user_function)Memoize a function by hashable arguments. A cache hit returns the stored result and does not run the function body again, so side effects are also cached.
| Parameter | Description |
|---|---|
maxsize | The maximum number of distinct calls to keep. None disables eviction. cache() is the unbounded form. |
typed | If True, values of different types are stored separately, so 3 and 3.0 are distinct keys. |
Returns: A wrapped function. The wrapper has cache_info() and cache_clear() methods. cache_info() returns a named tuple of hits, misses, maxsize, and currsize.
Raises
TypeError— Raised when an argument is unhashable, for example a list or a dict. The message is typically "unhashable type: 'list'".
- In the example, add(1, 2) is called twice in the printed sequence but appears only once in the side-effect log, because the second call is a cache hit.
- Do not cache a function whose result depends on global state, time, or I/O unless you are prepared for stale values.
from functools import cache, lru_cache
calls = []
@lru_cache(maxsize=2)
def add(a, b):
calls.append((a, b))
return a + b
print(add(1, 2), add(1, 2), add(2, 3), add(1, 2))
print(calls)
print(add.cache_info())
try:
add([1], 2)
except TypeError as exc:
print(f"{type(exc).__name__}: {exc}")
side = []
@cache
def bump(n):
side.append(n)
return n + 1
print(bump(1), bump(1), side)Expected output
3 3 5 3
[(1, 2), (2, 3)]
CacheInfo(hits=2, misses=2, maxsize=2, currsize=2)
TypeError: unhashable type: 'list'
2 2 [1]