LRU Dict

1.4.1 · active · verified Fri Apr 10

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

Install

Imports

Quickstart

Initializes an LRU cache, demonstrates item insertion, eviction, access-based reordering, deletion, resizing, and updates. Includes examples of `items()`, `keys()`, `get_size()`, `set_size()`, and `in` operator usage.

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()}")

view raw JSON →