Is your function called over and over with the same arguments, recomputing from scratch every time? functools.lru_cache (and @cache, available since Python 3.9) remembers the results of previous calls — when it sees old arguments again, it returns the result immediately without running the function body. With a single decorator you eliminate a whole class of redundant computation. Use it when a function is expensive (recursive, heavy data processing) but gets called repeatedly.

The Problem

The classic example is recursive Fibonacci:

def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
# fib(35) recomputes the same fib(20) thousands of times

In real projects, this problem shows up in unexpected places: a string-normalization function called on every request with the same input, a config-parsing function re-run every loop, or an expensive computation shared by multiple views. Every call is a waste of CPU.

The Fix

Add one decorator, change zero lines of logic:

from functools import cache
@cache
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
fib(35) # first call: real computation
fib(35) # second call: served straight from cache
fib.cache_info() # CacheInfo(hits=34, misses=36, maxsize=None, currsize=36)

Why is it better? The decorator wraps the function with a dict mapping (arguments → result). Calling it again with old arguments is just a dict lookup — no computation. @cache is equivalent to lru_cache(maxsize=None) — an unbounded cache. Plain lru_cache keeps at most 128 of the most recent entries by default: when full, the least recently used entry is evicted (LRU), which suits long-running processes like web servers by avoiding RAM bloat.

Two important constraints: (1) arguments must be hashable — passing a list or dict raises TypeError: unhashable type, so convert them to tuple/frozenset first; (2) only cache pure functions — not ones with side effects (writing to a DB, sending email, calling APIs), not time- or random()-dependent functions, because on later calls the function body won’t run at all.

Apply It to Your Project

In a real web project, look for “expensive but repeated” functions: a complex query builder in Django, a template parser in Flask, or a heavy computed dependency in FastAPI whose inputs are just a few config strings. Put @lru_cache(maxsize=256) on top, prefer a concrete maxsize over unbounded on long-running processes, and add cache_clear() to your deploy routine or when the source data changes. Don’t confuse this with distributed caching: this is a per-process cache, not a replacement for Redis/Memcached when you need sharing across workers.

Related Posts

FAQ

@cache vs @lru_cache: what’s the difference?

@cache, available since Python 3.9, is equivalent to lru_cache(maxsize=None) — the cache never fills up and runs slightly faster. @lru_cache defaults to the 128 most recent entries and lets you tune maxsize and typed — safer for long-running processes.

What happens if I pass a list or dict to an @lru_cache function?

It raises TypeError: unhashable type because the cache does dict lookups. Fix: convert list to tuple, dict to frozenset (or a tuple of key-value pairs) before calling.

Does the cache eat RAM? When should I call cache_clear()?

Yes — the cache holds references to arguments and results until evicted or cleared. Call cache_clear() when the source data changes (e.g. reloading config) or periodically on long-running processes to prevent memory growth.

Is lru_cache thread-safe?

Yes — its internal data structures are consistent across threads. But it doesn’t guarantee “called exactly once”: two threads can both run the function with the same arguments before the first entry is stored.

Why shouldn’t I cache functions with side effects?

Because from the second call on, the body doesn’t run — the side effect is skipped. Example: a function that computes and also writes a log or sends an email — a cache hit would silently skip the logging and the email, causing hard-to-find logic bugs.

References