▶ Sign up free for the video, slides & prompts
The lesson below is open to all. Enter your email once to unlock every video, slide deck, prompt and code example on this device.
Checking…
Caching results
functools.lru_cache and when caching helps.
🎬 Video version coming soon — read it now
If a function is called again with the same inputs and gives the same answer, why calculate it twice? Caching stores results so repeat calls are instant.
lru_cache: one line
Without the cache, fib(40) makes over 300 million calls. With it, each value is calculated once. That's the difference between minutes and microseconds.
maxsize limits how many results are kept, discarding the least recently used. functools.cache is the same as lru_cache(maxsize=None).
Real uses
- Expensive calculations repeated with the same inputs
- Reading configuration or reference files that rarely change
- Slow API lookups where slightly old data is fine, such as currency rates or city coordinates
The rules
- Arguments must be hashable: numbers, strings and tuples work; lists and dicts don't. Convert with
tuple(my_list). - The function must be pure: same inputs, same output, no side effects. Don't cache something that sends an email or depends on the current time.
- Watch memory: an unbounded cache grows forever in a long-running server. Set a
maxsize. - Stale data: a cached result doesn't update when the real data changes. Clear it with
.cache_clear()or use a time-limited cache.
Caching to disk
lru_cache lives in memory and disappears when the program ends. For results that are expensive to recompute between runs, such as AI responses during development, save them:
While developing an AI script, this means re-runs don't pay for the same prompts again.
In one line
@lru_cache remembers results of pure functions; keep arguments hashable, bound the size, and use a disk cache to survive between runs.
Share with a friend