Sub topic 10
Measuring and clearing a cache
A cache you cannot observe is a cache you cannot trust. This chapter covers the two tools that functools attaches to every cached function: cache_info(), which reports how the cache is performing, and cache_clear(), which empties it.
This chapter assumes you can already apply @cache and @lru_cache(maxsize=...) to a function. It also assumes you know why the arguments must be hashable. Both tools work the same way on cache and lru_cache, because cache is lru_cache(maxsize=None) under a shorter name.
Reading cache_info()
Calling cache_info() on a cached function returns a named tuple with four fields.
| Field | Meaning |
|---|---|
| `hits` | Calls answered from the cache without running the function |
| `misses` | Calls that had to run the function |
| `maxsize` | The limit you configured, or `None` for an unbounded cache |
| `currsize` | The number of results stored right now |
The result is a snapshot. It does not update later, so call cache_info() again when you want fresh numbers.
from functools import lru_cache
@lru_cache(maxsize=128)
def slow_square(n):
return n * n
for n in [1, 2, 3, 1, 2, 3, 1, 2, 3, 4]:
slow_square(n)
info = slow_square.cache_info()
print(info) # CacheInfo(hits=6, misses=4, maxsize=128, currsize=4)
print(info.hits, info.misses) # 6 4
print(info.hits + info.misses) # 10, the number of callsThe ten calls use four distinct arguments. Each distinct argument misses once, and the other six calls hit. Because hits + misses equals the total number of calls, you can compute a hit rate from the two counters.
from functools import lru_cache
@lru_cache(maxsize=128)
def slow_square(n):
return n * n
def hit_rate(func):
info = func.cache_info()
total = info.hits + info.misses
return info.hits / total if total else 0.0
for n in [1, 2, 3, 1, 2, 3, 1, 2, 3, 4]:
slow_square(n)
print(f"{hit_rate(slow_square):.0%}") # 60%The if total guard avoids a division by zero on a cache that has not been called yet.
What the counters do and do not count
Hits and misses count every call to the cached function, including recursive calls made from inside it. Memoized Fibonacci shows this:
from functools import cache
@cache
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
fib(80)
print(fib.cache_info()) # CacheInfo(hits=78, misses=81, maxsize=None, currsize=81)There are 81 misses, one for each value from fib(0) to fib(80). Each miss for n >= 2 makes two recursive calls, so there are 79 × 2 + 1 = 159 calls in total. That leaves 159 − 81 = 78 hits. Without the cache, the same call would run the function billions of times.
If the function raises an exception, nothing is stored. The next call with the same arguments runs the function again.
You can also read the configuration back with cache_parameters(), which returns a dictionary:
from functools import cache
@cache
def f(x):
return x
print(f.cache_parameters()) # {'maxsize': None, 'typed': False}How the counters change
Every call moves through the same decision. The diagram shows where each counter changes.
Eviction keeps currsize at or below maxsize. An unbounded cache never takes the eviction branch, so its currsize only grows.
Using the numbers to choose maxsize
The most useful job for cache_info() is tuning maxsize. A cache that is too small evicts entries before they are reused, and its hit rate collapses. The next experiment cycles through five keys with two different sizes.
from functools import lru_cache
def make_lookup(size):
@lru_cache(maxsize=size)
def lookup(key):
return key * 10
return lookup
for size in (4, 5):
lookup = make_lookup(size)
for _ in range(3):
for key in range(5):
lookup(key)
print(size, lookup.cache_info())The output is:
4 CacheInfo(hits=0, misses=15, maxsize=4, currsize=4)
5 CacheInfo(hits=10, misses=5, maxsize=5, currsize=5)With maxsize=4, the cache holds four of the five keys. Each new call evicts the key that the cycle will need next, so every call misses. This is called thrashing, and the cache adds overhead for no benefit. With maxsize=5, every key fits, so only the first pass misses.
Use these signs when reading the numbers:
- A low hit rate with
currsize == maxsizesuggests the cache is too small, or that the arguments rarely repeat. Increasingmaxsizehelps only in the first case. - A hit rate near zero with a large
currsizesuggests the arguments almost never repeat. Caching may not suit this function. - A high hit rate with
currsizewell belowmaxsizemeans the size is generous. You can lower it to save memory. - A
currsizethat keeps growing on an unboundedcacheis a memory leak waiting to happen. Switch tolru_cachewith a limit.
Measure with a realistic workload. A test that calls the function ten times tells you little about production traffic.
Clearing with cache_clear()
cache_clear() removes every stored result and resets hits and misses to zero. It takes no arguments and returns None.
from functools import lru_cache
@lru_cache(maxsize=2)
def square(n):
print(f"computing {n}")
return n * n
square(1)
square(2)
square(1) # cache hit
square(3) # evicts the least recently used entry, 2
square(2) # computed again
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 call square(1) is a hit and refreshes the entry for 1. When square(3) arrives, entry 2 is the oldest and is evicted. The later square(2) therefore misses and evicts 1. Four misses and one hit confirm that.
When to clear a cache
Clear a cache when the world the function reads from has changed. A cached function should be pure, which means the same arguments always give the same result. Reading configuration, files, or environment variables breaks that rule, and the cache will keep returning stale values.
import os
from functools import cache
@cache
def get_setting(name):
return os.environ.get(name, "unset")
os.environ["MODE"] = "dev"
print(get_setting("MODE")) # dev
os.environ["MODE"] = "prod"
print(get_setting("MODE")) # dev, a stale value from the cache
get_setting.cache_clear()
print(get_setting("MODE")) # prodCommon reasons to call cache_clear():
- Tests that must start from a known state. Clear the cache in a setup or teardown step so one test's results do not leak into another.
- A reload of configuration or data that the function depends on.
- A memory pressure event, when you would rather lose all entries than keep them.
- A benchmark, where you want to compare cold and warm timings.
Limits of cache_clear()
cache_clear() is all or nothing. There is no public way to remove one entry, so if one input changed you still have to clear every entry. If you need per-key invalidation, keep your own dictionary instead of using functools.
The clear affects only the function you call it on. Each decorated function has its own cache. A cached method is a special case, because the cache belongs to the function on the class and is shared by all instances:
from functools import lru_cache
class Converter:
@lru_cache(maxsize=32)
def scale(self, x):
return x * 2
a, b = Converter(), Converter()
a.scale(1)
b.scale(1)
print(Converter.scale.cache_info().currsize) # 2
Converter.scale.cache_clear()
print(Converter.scale.cache_info().currsize) # 0Both instances share one cache, and each cached call stores a reference to self, which keeps the instance alive. The call Converter.scale.cache_clear() clears entries for every instance at once.
Finally, the cache holds an internal lock for its own bookkeeping, so concurrent use does not corrupt it. The function itself can still run more than once at the same time for the same arguments, because the lock is not held while the function runs. Do not rely on misses as an exact count of function executions in threaded code.
Reaching the tools through another decorator
The cache_info and cache_clear attributes live on the object that cache returns. A decorator built with wraps replaces that object with a plain function. wraps copies the name, docstring, and __dict__ of the original, but the cache tools are not part of what it copies. The attributes are therefore missing from the outer function, and __wrapped__ is the way back to them.
import functools
from functools import cache
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"calling {func.__name__}{args}")
return func(*args, **kwargs)
return wrapper
@log_calls
@cache
def double(n):
return n * 2
double(4)
double(4)
print(hasattr(double, "cache_info")) # False
print(double.__wrapped__.cache_info())
# CacheInfo(hits=1, misses=1, maxsize=None, currsize=1)
double.__wrapped__.cache_clear()Both calls are logged, because log_calls is on the outside. The cache sees the same two calls, one miss and then one hit. Because the stacking order matters, you have two options:
- Keep
@log_callson top and reach the cache through__wrapped__, as above. - Put
@cacheon top of@log_calls. The cache functions are then directly available, and the log line appears only on misses, since hits never reach the logging wrapper.
Choose the order based on what you want to observe. If you are counting calls, put the logger on the outside. If you are counting real work, put it inside.
Common mistakes
- Reading
cache_info()once and treating it as live. It is a snapshot. - Judging a cache by
hitsalone. A large hit count means little if misses are also large, so compute the rate. - Calling
cache_clear()on a cached method and expecting it to affect one instance only. - Forgetting that a decorator on top hides
cache_info, which leads to anAttributeError. - Clearing on every request. That removes the benefit of the cache, since the hit rate will be near zero.
Exercise
A function decorated with @lru_cache(maxsize=3) is called with the arguments 1, 2, 3, 4, 1 in that order. What does cache_info() report afterward, and why?
Show answer
It reports CacheInfo(hits=0, misses=5, maxsize=3, currsize=3). The first three calls fill the cache. The call with 4 evicts the least recently used entry, which is 1. The final call with 1 therefore misses again and evicts 2. No call ever finds its key in the cache, so there are no hits.
Exercise
A function wrapped as @log_calls above @cache is named lookup. You call lookup.cache_clear() and get an AttributeError. Give two ways to fix it.
Show answer
The wrapper made by wraps does not carry the cache methods. You can call lookup.__wrapped__.cache_clear(), which reaches the cached function underneath. Or you can swap the order to @cache above @log_calls, so lookup is the cached object and has cache_clear directly.
Exercise
After warming up, a bounded cache shows hits=900, misses=100, maxsize=256, currsize=40. Should you raise maxsize? What is the hit rate?
Show answer
The hit rate is 900 / 1000 = 90%. You should not raise maxsize, because currsize is only 40, far below the limit of 256. The cache is not under eviction pressure, and a larger limit would not add hits. You could even lower it to save memory.