Functional Functions

functools.lru_cache()

Create a memoizing decorator with least-recently-used eviction for a bounded cache. Supports bare @lru_cache as well; arguments must be hashable. None makes the cache unbounded.

Formal Syntax & Structure

python syntaxpython
functools.lru_cache(maxsize=128, typed=False) or functools.lru_cache(user_function)

Parameters & Attributes

NameTypeDescription
maxsizeint or None or callableMaximum cached entries; None disables eviction. A callable supports the bare decorator form.
typedboolDistinguish argument types in cache keys when true.

Return Value

callable

The callable result described above.

Working Example

Example Snippetpython
import functools@functools.lru_cache(maxsize=2)def f(x): return x*xprint((f(2),f(2),f.cache_info().hits))
Python Reference