Sub topic 9
Bounding memory with lru_cache
This chapter assumes you can write and call Python functions, that you know the @ decorator syntax, and that you know which built-in types are hashable (a tuple is, a list is not). It also assumes you have seen functools.cache in the previous chapter. Here you will learn what lru_cache adds: a limit on how many results are stored, and a rule for deciding which result to throw away.
The problem with an unbounded cache
cache keeps every result it has ever computed. For a function with a small, fixed set of inputs, that is fine. For a function whose inputs come from users, files, or timestamps, the set of possible arguments has no limit. A long-running service that calls such a function with a fresh argument each time stores one more entry per call, and nothing ever removes it. Memory grows until the process is killed.
functools.lru_cache solves this by capping the number of stored entries. When the cache is full and a new result must be stored, it discards the entry that was least recently used. "LRU" stands for that rule.
Basic usage
You can apply lru_cache with an explicit size, with its default size, or without parentheses.
from functools import lru_cache
@lru_cache(maxsize=3)
def load(key):
print(f"loading {key}")
return key.upper()
for key in ["a", "b", "c", "a", "d", "b"]:
load(key)
print(load.cache_info())This prints:
loading a
loading b
loading c
loading d
loading b
CacheInfo(hits=1, misses=5, maxsize=3, currsize=3)The second "a" was a hit, so the function body did not run and nothing was printed. The call with "b" at the end printed loading b again because "b" had been evicted by then.
The three spellings are:
from functools import lru_cache
@lru_cache(maxsize=256) # explicit size
def f1(x): return x
@lru_cache # default size, 128 (Python 3.8+)
def f2(x): return x
@lru_cache() # same as above, older style
def f3(x): return x
print(f1.cache_info().maxsize, f2.cache_info().maxsize, f3.cache_info().maxsize)
# 256 128 128The bare form @lru_cache works from Python 3.8. In earlier versions you must write the parentheses, or Python passes your function in as maxsize and raises a TypeError.
How eviction works
The cache tracks the order in which entries were last used. Every hit moves an entry to the "most recent" end. Every miss adds a new entry at that end. When the cache already holds maxsize entries, the entry at the "least recent" end is removed to make room.
Reading a value counts as use. This is the difference between LRU and a simple first-in, first-out queue. An entry that you keep asking for stays in the cache, however old it is.
Now trace the example from the start of this chapter with maxsize=2.
from functools import lru_cache
@lru_cache(maxsize=2)
def square(n):
print(f"computing {n}")
return n * n
square(1) # miss, cache: 1
square(2) # miss, cache: 1, 2
square(1) # hit, 1 becomes most recent, cache: 2, 1
square(3) # miss, evicts 2 (least recent), cache: 1, 3
square(2) # miss again, evicts 1, cache: 3, 2
print(square.cache_info())
# CacheInfo(hits=1, misses=4, maxsize=2, currsize=2)
square.cache_clear()
print(square.cache_info())
# CacheInfo(hits=0, misses=0, maxsize=2, currsize=0)The hit on square(1) is what saved it from eviction. Had the third call not happened, square(3) would have evicted 1, the oldest entry. The next chapter covers cache_info() and cache_clear() in detail. Here they only let you see the effect of eviction.
The maxsize parameter
maxsize sets how many distinct argument combinations the cache may hold. It counts entries. It does not count bytes. A cache of 128 entries that each hold a 50 MB result can use over 6 GB.
| `maxsize` value | Behavior |
|---|---|
| `128` (default) | Keeps up to 128 entries and evicts the least recently used. |
| Any positive integer | Same rule with your chosen limit. |
| `None` | No limit and no eviction. This is the same as `functools.cache`. |
| `0` | Nothing is stored. Every call runs the function. Calls are still counted as misses. |
| Negative number | Treated as `0`. |
functools.cache(f) is documented as equivalent to lru_cache(maxsize=None)(f). It is a little faster than a bounded cache because it skips the bookkeeping that tracks recency. If the full set of inputs is small and known, as with the recursive Fibonacci example, use cache. If the set of inputs is open-ended, use lru_cache with a limit.
The documentation notes that an LRU cache performs best when maxsize is a power of two. This is a performance hint, not a correctness rule, and any positive size works.
Choosing a size
There is no formula, but these questions narrow it down:
- How many distinct inputs are "hot"? If a program repeatedly asks about 40 different keys, a
maxsizeof 64 keeps nearly all of them. A size of 10 would constantly evict entries that are about to be needed again. - How large is each result? Multiply the entry size by
maxsizeto get the worst-case memory use. - How expensive is a miss? A miss that costs a microsecond does not justify a large cache. A miss that costs a network round trip does.
- What does the hit rate look like? Run a realistic workload and read
cache_info(). If doublingmaxsizebarely changes the hit ratio, the extra memory is wasted.
How arguments become keys
The cache key is built from the arguments of the call. This has consequences beyond the hashability rule from the previous chapter.
Argument spelling matters
Calls that mean the same thing to you can be different keys to the cache.
from functools import lru_cache
@lru_cache(maxsize=None)
def area(width, height):
return width * height
area(2, 3)
area(width=2, height=3)
area(height=3, width=2)
print(area.cache_info())
# CacheInfo(hits=0, misses=3, maxsize=None, currsize=3)All three calls return 6, yet each one is a miss. Positional and keyword forms are distinct keys, and so are different orderings of the same keywords. If your callers use mixed styles, you waste cache entries and lower the hit rate. Pick one calling style for cached functions, or wrap the cached function in a small function that normalizes the arguments.
The typed parameter
By default, arguments that compare equal and hash equally share an entry. 3 and 3.0 are equal, so the second call gets the first call's result. That is a problem if the result type depends on the argument type. Pass typed=True to keep them apart.
from functools import lru_cache
@lru_cache(maxsize=8)
def half_untyped(x):
return x / 2
@lru_cache(maxsize=8, typed=True)
def half_typed(x):
return x / 2
for fn in (half_untyped, half_typed):
fn(2)
fn(2.0)
fn(2)
print(fn.cache_info())
# CacheInfo(hits=2, misses=1, maxsize=8, currsize=1)
# CacheInfo(hits=1, misses=2, maxsize=8, currsize=2)With typed=True, 2 and 2.0 get separate entries, which means more misses and more stored entries. Use it only when the argument type changes the result in a way you care about. For an int versus float difference in x / 2 it does not matter, because both give 1.0. It matters for something like str(x), where str(2) is "2" and str(2.0) is "2.0".
What is stored, and what that means
The cache stores a reference to the returned object, not a copy. Two callers who get the same cached list get the same list object. If one of them modifies it, the other sees the change.
from functools import lru_cache
@lru_cache(maxsize=4)
def defaults():
return ["red", "green"]
a = defaults()
a.append("blue")
print(defaults()) # ['red', 'green', 'blue']The function body ran once. After the append, the cached object itself is changed. Return immutable values such as tuples, strings, or numbers from cached functions. If you must return a mutable object, return a copy at the call site or build a new one on each call outside the cache.
A cache entry also keeps its arguments alive. If an argument is a large object, it stays in memory for as long as the entry is in the cache. Bounding maxsize bounds this as well.
Threads and concurrent misses
The cache is thread-safe. Concurrent calls cannot corrupt its internal state. But the function is not locked while it runs. If two threads call the function with the same new arguments at the same moment, both see a miss, and both run the function. Both results are stored, and the later one wins. For pure functions this wastes work but gives the right answer. For functions with side effects it can cause duplicated work, which is another reason to cache only pure functions.
Inspecting the cache settings
Python 3.9 added cache_parameters() to the wrapped function. It returns the settings the cache was built with.
from functools import lru_cache
@lru_cache(maxsize=32, typed=True)
def f(x):
return x
print(f.cache_parameters())
# {'maxsize': 32, 'typed': True}The wrapper also has __wrapped__, which points to the original undecorated function. Calling f.__wrapped__(5) runs the function without touching the cache, which is useful in tests and for timing the uncached version.
When to prefer lru_cache over cache
Use lru_cache with a limit when:
- the argument space is large or unbounded, such as user IDs, file paths, or search strings;
- the program runs for a long time, so even slow growth adds up;
- recently used inputs are likely to be used again soon (the pattern that LRU is designed for).
Use cache when the argument space is small and fixed, as in a recursive function over a bounded range.
LRU is a poor fit when access is a one-time scan over many distinct keys. Each new key evicts a useful old one, and no key is ever requested twice. The hit rate falls to zero while the cache still costs memory and time. Measure before keeping a cache.
Exercise
A function is decorated with @lru_cache(maxsize=2). It is called in this order: f(1), f(2), f(1), f(3), f(1), f(2). How many hits and misses does cache_info() report, and which keys are in the cache at the end?
Show answer
2 hits and 4 misses. f(1) and f(2) are misses, the second f(1) is a hit, f(3) is a miss that evicts 2, the next f(1) is a hit, and the final f(2) is a miss that evicts 3. The cache ends with keys 1 and 2, with currsize=2.
Exercise
A web service has a cached function get_profile(user_id) that returns a dictionary of about 200 KB. Traffic touches several million distinct user IDs per day, but 5,000 users account for most requests. Should you use cache or lru_cache, what maxsize would you start with, and what should you change about the return value?
Show answer
Use lru_cache, because cache would grow without limit across millions of IDs. Start with a maxsize around 5,000 to 8,192, which covers the hot users. That bounds memory at roughly 1 to 1.6 GB, so lower it if that is too much, and check the hit ratio from cache_info() under real traffic. Return an immutable structure, or copy the dictionary before callers modify it, because every caller receives the same cached object.