LRU Dict
lru-dict is a fixed-size dictionary-like container that evicts the Least Recently Used (LRU) items once its capacity limit is exceeded. It is implemented in C for performance and memory efficiency. The library is currently at version 1.4.1 and maintains an active release cadence, focusing on Python version compatibility and minor feature enhancements.
Warnings
- breaking Older versions of `lru-dict` (e.g., 1.1.8 and earlier) did not support newer Python versions like 3.11+. Upgrading to `lru-dict >=1.4.0` is required for Python 3.11+ compatibility.
- gotcha `lru-dict` is a C-implemented cache and is explicitly noted as not being thread-safe in older documentation. While not always explicitly stated in newer versions, C extensions often require explicit synchronization for thread-safe operations if not designed for it. Use with caution in multi-threaded environments or implement external locking.
- gotcha `lru-dict` provides a dictionary-like container, distinct from `functools.lru_cache`, which is a function decorator for memoization. Users expecting automatic function result caching should use `functools.lru_cache` instead, or wrap `lru-dict` in a custom caching decorator.
- gotcha Like standard Python dictionaries, `lru-dict` keys must be hashable. Using mutable objects (e.g., lists, dictionaries) as keys will result in a `TypeError`. Modifying a mutable key after insertion can lead to incorrect cache behavior.
Install
-
pip install lru-dict
Imports
- LRU
from lru import LRU
Quickstart
from lru import LRU
l = LRU(5) # Create an LRU container with a capacity of 5
for i in range(5):
l[i] = str(i)
print(f"Initial LRU state: {l.items()}")
# Expected: [(4, '4'), (3, '3'), (2, '2'), (1, '1'), (0, '0')]
l[5] = '5' # Add a new item, '0' (LRU) should be evicted
print(f"After adding 5: {l.items()}")
# Expected: [(5, '5'), (4, '4'), (3, '3'), (2, '2'), (1, '1')]
l[3] # Accessing an item makes it Most Recently Used (MRU)
print(f"After accessing 3: {l.items()}")
# Expected: [(3, '3'), (5, '5'), (4, '4'), (2, '2'), (1, '1')]
del l[4] # Delete an item
print(f"After deleting 4: {l.items()}")
# Expected: [(3, '3'), (5, '5'), (2, '2'), (1, '1')]
l.set_size(3) # Resize the LRU cache
print(f"After resizing to 3: {l.items()}")
# Expected: [(3, '3'), (5, '2'), (2, '1')] (order depends on eviction policy details for resize)
print(f"Current size: {l.get_size()}") # Get current capacity
print(f"Has key 5: {5 in l}")
l.update({1: 'one_updated'}) # Update an existing item
print(f"After updating 1: {l.items()}")