Skip to content
GreenSnippets

Cache function results with functools.lru_cache

Memoize pure functions with a bounded least-recently-used cache and inspect or clear it.

Python
from functools import lru_cache


@lru_cache(maxsize=256)
def fibonacci(n):
    return n if n < 2 else fibonacci(n - 1) + fibonacci(n - 2)

Example / expected output

Output
fibonacci(80)  # 23416728348467685, computed in microseconds

How it works

lru_cache is in the standard library, thread-safe and fast. Arguments must be hashable. Always set maxsize for functions with many distinct inputs, otherwise memory grows without bound. cache_info() shows hits and misses; cache_clear() resets it.