Reuse a result with a cache

Lesson 15 of 20 · Functional Python: values, behavior, and choices

Memoization stores results under their inputs so a repeated call can reuse them. The standard-library lru_cache is a decorator that handles this bookkeeping. LRU means least recently used: a bounded cache evicts the entry least recently used when it needs space.

from functools import lru_cache

@lru_cache(maxsize=2)
def tiles(side):
    print("calculate", side)
    return side * side

print(tiles(4))
print(tiles(4))
print(tiles.cache_info().hits, tiles.cache_info().misses)
calculate 4
16
16
1 1

The first call misses and runs the body; the second hits and skips it, including the print. This print is present to show the mechanism, not a good effect to rely on in cached work. Arguments must be hashable; lists cannot be cache keys directly. cache_clear() removes stored entries and resets statistics.

Caching trades memory and lookup cost for avoided work; measure whether it helps. It retains references to keys and results until eviction or clearing. Avoid caching calls whose effects must happen each time, whose result depends on changing external state, or which must return a fresh mutable object. Different call patterns can make separate entries. A thread-safe cache structure does not promise the underlying function runs only once on concurrent misses.

Chapter index