Master programming syntax, solve interactive challenges & run live code in Syntaxis Explore Arena →
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

NameTypeDescription
maxsizeint | NoneMaximum entries in cache. None = unbounded.
typedboolIf 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.