Codectionary / Developer documentation / Python

Bounded Memoization with lru_cache

lru_cache stores results by arguments and evicts least-recently-used entries when its size limit is reached. It suits repeated pure calculations with hashable inputs. Run as a Python 3.11+ script.

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)
  1. Expected output: 55 55 1
  2. 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

Specifications & further reading