Syntax
@lru_cache(maxsize=128)Examples
Bounded Memoization with lru_cache
Run as a Python 3.11+ script.
from functools import lru_cache
@lru_cache(maxsize=32)
def triangular(n):
return n * (n + 1) // 2
print(triangular(10))
print(triangular(10))
print(triangular.cache_info().hits)- Expected output: 55 55 1
- The second call with 10 reuses the stored result. cache_info exposes hits and misses so caching behavior can be measured.
Best practices
- Avoid caching functions whose results depend on mutable external state.
- Choose a bounded size and clear caches when their underlying data becomes stale.
Runtime & versions
Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Python language reference