Sub topic 14
Built-in options: OrderedDict and functools.lru_cache
This chapter assumes you have built the hash map plus doubly linked list LRUCache from the earlier chapters. You should know Python classes, dictionaries, and Big-O notation. Here you compare your hand-built cache with two tools in the standard library.
OrderedDict as a ready-made LRU structure
collections.OrderedDict is a dictionary that remembers insertion order. Internally it pairs a hash table with a doubly linked list, which is the same design you built by hand. That means it offers two operations you need:
move_to_end(key)moves an entry to the most recent end in O(1).popitem(last=False)removes the oldest entry in O(1).
Here is the cache rewritten with it:
from collections import OrderedDict
class OrderedDictLRUCache:
def __init__(self, capacity):
if capacity <= 0:
raise ValueError("capacity must be positive")
self.capacity = capacity
self.data = OrderedDict()
def get(self, key):
if key not in self.data:
return None
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.capacity:
self.data.popitem(last=False)The order is: the most recent key sits at the end, and the least recent sits at the front. This is the reverse of your list, where the most recent node sits next to the head.
put handles both cases in one path. Assigning to an existing key updates its value, and assigning a new key appends it. Then move_to_end marks it as most recent. Eviction runs only when the size exceeds the capacity.
The cache behaves the same as your version:
cache = OrderedDictLRUCache(2)
cache.put(1, "a")
cache.put(2, "b")
print(cache.get(1)) # a
cache.put(3, "c") # evicts key 2
print(cache.get(2)) # None
print(cache.get(3)) # cfunctools.lru_cache
functools.lru_cache is a different kind of tool. It does not give you a cache object with get and put. It is a decorator that caches the results of a function, keyed by the function's arguments.
from functools import lru_cache
@lru_cache(maxsize=2)
def square(n):
print(f"computing {n}")
return n * n
print(square(2)) # computing 2, then 4
print(square(2)) # 4, served from the cache
print(square(3)) # computing 3, then 9
print(square(4)) # computing 4, then 16; evicts the entry for 2
print(square(2)) # computing 2 again, then 4
print(square.cache_info())The call cache_info() reports hits, misses, maxsize, and the current size. cache_clear() empties the cache.
Keep these limits in mind:
- The arguments must be hashable, because they become dictionary keys.
- The function should be pure. If it depends on outside state, cached results can go stale.
- Instance methods keep a reference to
selfin the cache, which can keep objects alive longer than you expect. maxsize=Noneremoves the bound, so the cache grows without limit.
Choosing between the three
| Option | Best for | Control over eviction |
|---|---|---|
| Hand-built map and list | Learning, or custom behavior such as hooks on eviction | Full |
| `OrderedDict` | A cache object with explicit `get` and `put` | High, with little code |
| `functools.lru_cache` | Memoizing a pure function | Low, only `maxsize` |
In production, prefer the built-ins unless you need behavior they lack. The hand-built version is still worth knowing. It shows why OrderedDict is fast, and it is the basis for variants such as TTL expiry.
Exercise
You need to cache the results of an expensive, pure function parse(text) that takes a string. You also need to remove one specific entry when a record is deleted. Is functools.lru_cache a good fit, and what would you use instead?
Show answer
lru_cache handles the pure function and the hashable string argument, but it cannot remove a single entry. It only offers cache_clear() for the whole cache. Use an OrderedDict based cache with a delete method that calls self.data.pop(key, None), or extend your hand-built cache.