Skip to main content

How to Cache a Function's Result in Python with functools.lru_cache

· 4 min read
Jagdish Kumawat
Founder @ Dewiride

Some functions are slow or touch a file, and their answer doesn't change while your program runs. functools.lru_cache remembers what a function returned, so the work happens once and every later call with the same arguments gets the saved result. This guide caches a small price list, with real output from Python 3.15.2.

Syntax​

Syntax
from functools import lru_cache


@lru_cache
def <function_name>(<arguments>):
...
PartWhat it means
from functools import lru_cacheImports the decorator from Python's standard library
@lru_cachePlaced on the line above def, it wraps the function with a cache
<function_name>(<arguments>)Your function. Each different set of arguments gets its own saved result
@lru_cache(maxsize=<n>)Optional form: keep at most n results (the default is 128); maxsize=None keeps them all

Python's functools documentation describes it as a "Decorator to wrap a function with a memoizing callable that saves up to the maxsize most recent calls. It can save time when an expensive or I/O bound function is periodically called with the same arguments." The wrapped function also gets a cache_info() method, "a named tuple showing hits, misses, maxsize and currsize".

Prerequisites​

  • uv and Python. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with uv init.

Step 1: Write the Script​

load_price_list() prints a line each time its body really runs, so you can see when the cache answers instead:

cache_result.py
from functools import lru_cache


@lru_cache
def load_price_list():
print("Reading the price list...")
return {"tent": 199, "stove": 49}


print(load_price_list()["tent"])
print(load_price_list()["stove"])
print(load_price_list.cache_info())

The cache_result.py script in a macOS-style code window: load_price_list is decorated with @lru_cache, prints a message and returns a dictionary of two prices, then the script calls it twice and prints cache_info().

The function is called twice, once for the tent's price and once for the stove's.

Step 2: Run It​

Terminal
uv run python cache_result.py
Output
Reading the price list...
199
49
CacheInfo(hits=1, misses=1, maxsize=128, currsize=1)

The output in a terminal: Reading the price list appears once, then 199 and 49, then CacheInfo with hits=1, misses=1, maxsize=128 and currsize=1.

Reading the price list... appears once. The first call ran the body (a miss) and saved the dictionary; the second call found it in the cache (a hit) and returned it without running the body. maxsize=128 is the default size, and currsize=1 means one result is stored, because a function with no arguments has only one possible call.

Common Mistakes​

MistakeWhat happensDo this instead
Caching a function whose answer should change, such as one that reads the clockEvery call after the first returns the old answerCache only functions whose result stays the same for the same arguments
Changing the returned dictionary or listThe change is saved too, because every call gets the same objectTreat the cached result as read-only, or return a copy
Passing a list or dictionary as an argumentTypeError: unhashable type: 'list', because the cache uses the arguments as a dictionary keyPass hashable values such as strings, numbers or tuples

Troubleshooting​

SymptomLikely causeFix
The function's body still runs every timeEach call uses different argumentsCheck with cache_info(): only misses grows
You need the body to run again, for example after a file changedThe cache keeps the first result until the program endsCall load_price_list.cache_clear()

FAQ​

What does "LRU" mean?​

Least recently used. When the cache is full (maxsize results), the result used longest ago is dropped to make room.

Is @lru_cache the same as @functools.cache?​

functools.cache is lru_cache(maxsize=None): it never drops results. For a function with no arguments, like the one here, both store exactly one result.

Does the cache last after the program ends?​

No. It lives in memory, so the next run starts empty.

Conclusion​

With @lru_cache on load_price_list(), the price list was read once and the second call came from the cache, which cache_info() confirmed with one miss and one hit.

Additional Resources​