Skip to content
IT Vizag
← Async & Performance

▶ 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

Lesson 4 of 10 · 2 min read

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

🔒 Code example: sign up free (above) to unlock it.

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
🔒 Code example: sign up free (above) to unlock it.

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:

🔒 Code example: sign up free (above) to unlock it.

While developing an AI script, this means re-runs don't pay for the same prompts again.

Tip: AI providers also offer prompt caching on their side, which makes repeated long prompts (like a big document you ask many questions about) cheaper and faster. Look it up when your prompts get large.

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.

Saved on this device. Sign in to keep progress everywhere.

Share with a friend