Reference / Python
functools.lru_cache
Decorator that wraps a function with a memoizing callable that saves up to the maxsize most recent calls.
Syntax
@lru_cache(maxsize=128, typed=False)Parameters
| Name | Type | Description |
|---|---|---|
| maxsize | int | None | Maximum entries in cache. None = unbounded. |
| typed | bool | If True, different typed arguments cached separately (e.g. 3 vs 3.0). |
Examples
Memoizing Fibonacci
from functools import lru_cache
@lru_cache(maxsize=256)
def fib(n: int) -> int:
if n < 2: return n
return fib(n - 1) + fib(n - 2)
print(fib(50))
print(fib.cache_info())Cached function arguments must be hashable.