Caching
suggest changeCaching means storing the result of an expensive operation so that later requests for the same thing are answered from memory. When a cache is applied to a pure function and keyed by its arguments, it's also called memoization.
Python has good caching tools built in:
- a plain
dictfor small, hand-written caches functools.cacheandfunctools.lru_cachefor memoizing functionsfunctools.cached_propertyfor computing an attribute once per objectcollections.OrderedDictif you need to build your own eviction policy
This article covers:
- memoizing with a dictionary
@cacheand@lru_cache: size limits, statistics, clearing,typed- how cache keys are built and why arguments must be hashable
- pitfalls: mutable results, methods, call patterns
cached_property- time-based expiry (TTL) and the
cachetoolspackage - caching async functions
- persistent caching on disk
See lru cache for a short introduction to @lru_cache.
Memoizing with a dictionary
The simplest cache is a dictionary that maps arguments to results:
_cache = {}
def slow_square(n):
if n in _cache:
return _cache[n]
print(f"computing {n}")
result = n * n
_cache[n] = result
return result
print(slow_square(4))
print(slow_square(4))
print(slow_square(5))
print(_cache)
computing 4
16
16
computing 5
25
{4: 16, 5: 25}
This works, but it mixes the caching logic with the function's real work, the cache grows forever, and you have to write it again for every function. The functools decorators solve all three problems.
functools.cache
@cache (Python 3.9+) wraps a function in an unbounded cache. Recursive functions benefit the most, because each sub-result is computed only once:
from functools import cache
calls = 0
@cache
def fib(n):
global calls
calls += 1
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(80))
print(calls)
print(fib.cache_info())
23416728348467685
81
CacheInfo(hits=78, misses=81, maxsize=None, currsize=81)
Without the cache, fib(80) would make about 10^16 calls and never finish. With it, the function body runs exactly 81 times, once for each value from 0 to 80.
The speed difference is dramatic even for small inputs:
import timeit
from functools import cache
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
@cache
def fib_cached(n):
return n if n < 2 else fib_cached(n - 1) + fib_cached(n - 2)
print(f"plain : {timeit.timeit(lambda: fib(25), number=10):.3f}s")
print(f"cached: {timeit.timeit(lambda: fib_cached(25), number=10):.6f}s")
Typical output (your numbers will differ):
plain : 0.071s
cached: 0.000020s
@cache is the same as @lru_cache(maxsize=None). It's slightly faster than a bounded LRU cache because it never has to track usage order, but it never forgets anything either. Use it when the set of possible arguments is small or bounded.
functools.lru_cache
@lru_cache(maxsize=N) keeps at most N results. When the cache is full, the least recently used entry is thrown away. The default maxsize is 128.
from functools import lru_cache
@lru_cache(maxsize=3)
def load(name):
print(f" loading {name}")
return name.upper()
for name in ["a", "b", "c", "a", "d", "b"]:
print(name, "->", load(name))
print(load.cache_info())
print(load.cache_parameters())
load.cache_clear()
print(load.cache_info())
loading a
a -> A
loading b
b -> B
loading c
c -> C
a -> A
loading d
d -> D
loading b
b -> B
CacheInfo(hits=1, misses=5, maxsize=3, currsize=3)
{'maxsize': 3, 'typed': False}
CacheInfo(hits=0, misses=0, maxsize=3, currsize=0)
Walk through it: after a, b, c the cache is full. Asking for a again is a hit and makes a the most recently used entry. Loading d evicts the least recently used one, which is b, so the next b is a miss.
The wrapped function gets these extra attributes:
| Attribute | Purpose |
|---|---|
f.cache_info() |
hits, misses, maxsize and current size |
f.cache_clear() |
empty the cache |
f.cache_parameters() |
the maxsize and typed settings (3.9+) |
f.__wrapped__ |
the original function, to call it bypassing the cache |
cache_info() is the tool to check whether a cache is doing its job. A low hit ratio means you're paying for memory without saving any work.
Since Python 3.8 you can write @lru_cache without parentheses to get the default size of 128.
The typed option
By default, arguments that compare equal share a cache entry, so 2 and 2.0 give the same result. With typed=True, arguments of different types are cached separately:
from functools import lru_cache
@lru_cache
def scale(x, factor):
return f"{x!r} * {factor!r} = {x * factor!r}"
print(scale(2, 10))
print(scale(2.0, 10)) # equal to (2, 10), so cache hit
print(scale.cache_info())
@lru_cache(typed=True)
def scale_typed(x, factor):
return f"{x!r} * {factor!r} = {x * factor!r}"
print(scale_typed(2, 10))
print(scale_typed(2.0, 10))
print(scale_typed.cache_info())
2 * 10 = 20
2 * 10 = 20
CacheInfo(hits=1, misses=1, maxsize=128, currsize=1)
2 * 10 = 20
2.0 * 10 = 20.0
CacheInfo(hits=0, misses=2, maxsize=128, currsize=2)
Without typed=True, scale(2.0, 10) returned the cached int result, which is wrong if the return type matters to the caller.
Cache keys and hashable arguments
The cache is a dictionary keyed by the function's arguments, so every argument must be hashable. Lists, dicts and sets can't be used:
from functools import cache
@cache
def total(numbers):
return sum(numbers)
print(total((1, 2, 3)))
try:
total([1, 2, 3])
except TypeError as e:
print("TypeError:", e)
6
TypeError: unhashable type: 'list'
Convert the argument before calling the cached function: tuple(lst), frozenset(s) or tuple(sorted(d.items())). A common pattern is to keep a public function that accepts anything and a private cached function that takes the hashable form:
from functools import cache
def total(numbers):
return _total(tuple(numbers))
@cache
def _total(numbers):
return sum(numbers)
The key is built from positional and keyword arguments as they were passed. Calls that mean the same thing but are written differently get separate cache entries:
from functools import cache
@cache
def greet(name, punctuation="!"):
print(" computing")
return f"Hello, {name}{punctuation}"
greet("Ann")
greet("Ann", "!")
greet("Ann", punctuation="!")
greet(name="Ann")
print(greet.cache_info())
computing
computing
computing
computing
CacheInfo(hits=0, misses=4, maxsize=None, currsize=4)
The result is still correct, just cached four times. If a cached function is called from many places, pick one calling style.
Pitfall: mutable return values
The cache returns the same object every time. If the caller modifies it, the cached value changes for everyone:
from functools import cache
@cache
def get_config():
print("reading config")
return {"debug": False, "tags": ["a"]}
cfg = get_config()
cfg["debug"] = True
cfg["tags"].append("b")
print(get_config())
reading config
{'debug': True, 'tags': ['a', 'b']}
Return immutable values from cached functions (tuples, frozenset, frozen dataclasses, types.MappingProxyType), or have callers make a copy with copy.deepcopy() before changing anything.
Pitfall: caching methods
Putting @lru_cache on a method works, but self becomes part of the cache key. The cache lives on the class, so it keeps a reference to every instance it has seen, and those objects aren't freed until their entries are evicted:
import gc
from functools import lru_cache
class Report:
def __init__(self, name):
self.name = name
@lru_cache(maxsize=None)
def render(self):
return f"report {self.name}"
def __del__(self):
print(f"freed {self.name}")
r = Report("q3")
r.render()
del r
gc.collect()
print("after del:", Report.render.cache_info())
Report.render.cache_clear()
print("done")
after del: CacheInfo(hits=0, misses=1, maxsize=None, currsize=1)
freed q3
done
The object survived del and garbage collection; it was freed only when the cache was cleared. In a long-running program, this is a memory leak. Also, self must be hashable, and clearing the cache clears it for all instances.
Better options:
- if the method takes no arguments, use
cached_property(next section) - if it takes arguments, keep a cache dictionary on the instance, so it dies with the object
- move the computation into a module-level cached function that takes only the values it needs
A per-instance cache:
class Report:
def __init__(self, name):
self.name = name
self._cache = {}
def render(self, fmt):
if fmt not in self._cache:
print(f" rendering {fmt}")
self._cache[fmt] = f"<{fmt}> report {self.name}"
return self._cache[fmt]
def __del__(self):
print(f"freed {self.name}")
r = Report("q3")
r.render("html")
r.render("html")
del r
print("done")
rendering html
freed q3
done
functools.cached_property
@cached_property (3.8+) turns a method into an attribute that is computed on first access and then stored in the instance's __dict__. Later accesses are ordinary attribute lookups:
from functools import cached_property
import statistics
class Dataset:
def __init__(self, values):
self.values = values
@cached_property
def stdev(self):
print(" computing stdev")
return statistics.stdev(self.values)
d = Dataset([2, 4, 4, 4, 5, 5, 7, 9])
print(d.stdev)
print(d.stdev)
print(d.__dict__)
d.values.append(100)
del d.stdev # invalidate
print(d.stdev)
computing stdev
2.138089935299395
2.138089935299395
{'values': [2, 4, 4, 4, 5, 5, 7, 9], 'stdev': 2.138089935299395}
computing stdev
31.729761703766037
Because the value is stored on the instance, it's freed together with the object. To invalidate it, del the attribute; the next access recomputes it.
Things to know:
- It needs a
__dict__, so it doesn't work on classes that define__slots__without__dict__. - Unlike
property, the value can be overwritten by assignment (d.stdev = 0). - Since 3.12 it no longer holds a lock, so two threads may both compute the value the first time. That's harmless for pure computations.
For regular properties that are recomputed on each access, see Property objects.
Writing your own LRU cache
OrderedDict remembers insertion order and can move a key to the end in O(1), which is all you need for an LRU policy:
from collections import OrderedDict
class LRUCache:
def __init__(self, maxsize):
self.maxsize = maxsize
self.data = OrderedDict()
def get(self, key, default=None):
if key not in self.data:
return default
self.data.move_to_end(key)
return self.data[key]
def put(self, key, value):
self.data[key] = value
self.data.move_to_end(key)
if len(self.data) > self.maxsize:
self.data.popitem(last=False)
c = LRUCache(2)
c.put("a", 1)
c.put("b", 2)
c.get("a") # "a" is now most recently used
c.put("c", 3) # evicts "b"
print(list(c.data.items()))
print(c.get("b"))
[('a', 1), ('c', 3)]
None
A hand-written cache like this is useful when the key isn't simply the function arguments, for example when you cache by URL but also want to store the response headers.
Expiring entries: TTL caches
lru_cache never expires entries by age. For data that goes stale, such as exchange rates or API responses, you want a time to live (TTL). A small decorator does it:
import time
from functools import wraps
def ttl_cache(seconds):
def decorator(func):
cache = {}
@wraps(func)
def wrapper(*args):
now = time.monotonic()
hit = cache.get(args)
if hit is not None and now - hit[1] < seconds:
return hit[0]
value = func(*args)
cache[args] = (value, now)
return value
wrapper.cache_clear = cache.clear
return wrapper
return decorator
@ttl_cache(seconds=0.5)
def exchange_rate(currency):
print(f" fetching {currency}")
return {"EUR": 1.08, "GBP": 1.27}[currency]
print(exchange_rate("EUR"))
print(exchange_rate("EUR"))
time.sleep(0.6)
print(exchange_rate("EUR"))
fetching EUR
1.08
1.08
fetching EUR
1.08
Use time.monotonic(), not time.time(), so changes to the system clock don't break expiry. This version never removes expired entries it doesn't look up again, so it's only suitable for a small set of keys.
The cachetools package
For production use, the third-party cachetools package (pip install cachetools) provides TTLCache, LRUCache, LFUCache and others, plus a @cached decorator:
import time
from cachetools import TTLCache, cached
@cached(cache=TTLCache(maxsize=1024, ttl=0.5))
def exchange_rate(currency):
print(f" fetching {currency}")
return {"EUR": 1.08, "GBP": 1.27}[currency]
print(exchange_rate("EUR"))
print(exchange_rate("EUR"))
time.sleep(0.6)
print(exchange_rate("EUR"))
print(exchange_rate.cache)
fetching EUR
1.08
1.08
fetching EUR
1.08
TTLCache({('EUR',): 1.08}, maxsize=1024, currsize=1)
TTLCache has both a size limit and an age limit. Unlike functools.lru_cache, cachetools caches aren't thread-safe on their own; pass lock=threading.Lock() to @cached when using them from several threads.
Caching async functions
@lru_cache doesn't work on async def functions. It caches the coroutine object, and a coroutine can be awaited only once:
import asyncio
from functools import lru_cache
@lru_cache
async def fetch(n):
await asyncio.sleep(0.01)
return n * 10
async def main():
print(await fetch(1))
try:
print(await fetch(1))
except RuntimeError as e:
print("RuntimeError:", e)
asyncio.run(main())
10
RuntimeError: cannot reuse already awaited coroutine
Cache a Task instead. A task can be awaited any number of times, and concurrent callers asking for the same key share one in-flight request:
import asyncio
from functools import wraps
def async_cache(func):
tasks = {}
@wraps(func)
def wrapper(*args):
if args not in tasks:
tasks[args] = asyncio.ensure_future(func(*args))
return tasks[args]
return wrapper
@async_cache
async def fetch_user(user_id):
print(f" fetching user {user_id}")
await asyncio.sleep(0.1)
return {"id": user_id, "name": f"user{user_id}"}
async def main():
# three concurrent calls, one fetch
results = await asyncio.gather(fetch_user(1), fetch_user(1), fetch_user(2))
print(results)
print(await fetch_user(1))
asyncio.run(main())
fetching user 1
fetching user 2
[{'id': 1, 'name': 'user1'}, {'id': 1, 'name': 'user1'}, {'id': 2, 'name': 'user2'}]
{'id': 1, 'name': 'user1'}
Two caveats: a task that raised an exception stays cached, so remove failed tasks if you want retries, and tasks belong to one event loop, so don't share this cache across asyncio.run() calls. See asyncio module for background.
Persistent caching on disk
In-memory caches disappear when the program exits. For results that are expensive to compute and stable over time, store them on disk. The standard library shelve module gives you a persistent dictionary with string keys:
import shelve
import time
def disk_cached(path):
def decorator(func):
def wrapper(key):
with shelve.open(path) as db:
if key in db:
return db[key]
value = func(key)
db[key] = value
return value
return wrapper
return decorator
@disk_cached("thumbnails.db")
def make_thumbnail(filename):
print(f" processing {filename}")
time.sleep(0.2)
return f"thumb-of-{filename}"
print(make_thumbnail("cat.jpg"))
print(make_thumbnail("cat.jpg"))
First run:
processing cat.jpg
thumb-of-cat.jpg
thumb-of-cat.jpg
Second run, the result comes from disk:
thumb-of-cat.jpg
thumb-of-cat.jpg
shelve uses pickle, so values must be picklable and you should only open files you trust. It's not safe for concurrent writers. For larger projects, the third-party diskcache package or a SQLite table are more robust choices.
Thread safety
lru_cache and cache keep their internal data structures consistent when called from several threads. They don't prevent the wrapped function from running more than once: if two threads ask for the same uncached key at the same time, both compute it and the last one to finish wins. For pure functions that's only wasted work. If the computation must happen only once, guard it with a lock.
When to cache
Caching trades memory for speed and adds a new source of bugs: stale data. A cache is a good fit when:
- the function is pure: the same arguments always give the same result, with no side effects
- it is expensive relative to a dictionary lookup
- it is called repeatedly with the same arguments (check
cache_info())
Don't cache functions that depend on the current time, random numbers, files or databases that change, unless you add expiry or explicit invalidation.
Summary
| Need | Use |
|---|---|
| Memoize a function, small set of inputs | @functools.cache |
| Memoize with bounded memory | @functools.lru_cache(maxsize=N) |
Treat 1 and 1.0 as different |
@lru_cache(typed=True) |
| Check cache effectiveness | f.cache_info() |
| Reset a cache | f.cache_clear() |
| Call without the cache | f.__wrapped__(...) |
| Compute an attribute once per object | @functools.cached_property |
| Cache per instance with arguments | a dict stored on self |
| Expire entries after a time | cachetools.TTLCache or a TTL decorator |
| Cache async functions | cache asyncio.Task objects |
| Keep results across runs | shelve, SQLite or diskcache |