Cache eviction algorithms and implementing an LRU cache in Python

Django Caching Patterns November 13, 2026 python

In Redis this is configured with maxmemory-policy (allkeys-lru, allkeys-lfu, volatile-ttl...).

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# ======================================================================
# Q: What are cache eviction algorithms, and how do you implement an LRU cache
# in Python?
#
# In Redis this is configured with maxmemory-policy (allkeys-lru, allkeys-lfu,
# volatile-ttl...). A classic question is to implement an LRU cache in Python:
# ======================================================================

from collections import OrderedDict

class LRUCache:
    def __init__(self, capacity):
        self.capacity, self.data = capacity, OrderedDict()
    def get(self, key):
        if key not in self.data:
            return None
        self.data.move_to_end(key)          # most recently used
        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)    # evict the least recently used