Why caching is needed, and in-memory cache
standardbeginnerA cache stores the result of a slow operation so the next request for the same thing skips the work. An in-memory cache keeps that result inside the running process — a dict, or functools.lru_cache — so lookups cost a hash, not a database query or a computation.
Think of it as
Caching is a sticky note with an answer already written on it, next to the phone. Without it, you redial and ask the same question every time. The note only helps as long as it stays true — that tension (fast, but possibly stale) is the whole subject of this section.
What we're doing: Show that lru_cache actually skips re-running the function body on a repeated call, and reports the hit/miss counts.
- 5
- @lru_cache(maxsize=128) wraps slow_square so results are stored by argument, up to 128 distinct arguments.
- 6
- calls["n"] increments only when the wrapped body actually runs — a cache hit skips this entirely.
- 11
- slow_square(4) again returns the stored result — calls["n"] does not increment a second time.
16
16
25
2
CacheInfo(hits=1, misses=2, maxsize=128, currsize=2)Why this works: The function body ran only twice (calls["n"] == 2) even though slow_square was called three times — the second call with 4 was served from lru_cache's internal dict without re-executing the function, which is exactly what CacheInfo(hits=1, misses=2, ...) confirms.
Caching a plain dict with no size limit
Wrong
Better
What you see: Memory usage grows without bound as more distinct keys are seen — eventually an OOM kill in a long-running process, with no error until then.
Why: A plain dict used as a cache has no eviction policy — every new key adds an entry that is never removed. lru_cache(maxsize=N) bounds memory by discarding the least-recently-used entry once the cache is full.
Remember: A cache saves a slow result in a fast place; an in-memory cache is the fastest kind but lives only in the current process and vanishes on restart.
See also: redis cache · cache aside write through write back · ttl and cache invalidation

