repoze.lru: Tiny LRU Cache
repoze.lru is a light-weight LRU (Least Recently Used) cache implementation for Python, including both an `LRUCache` object and an `lru_cache` decorator. It efficiently evicts less frequently used keys and values to manage memory. The current version 0.7, released in 2017, maintains a stable and slow release cadence, focusing on core functionality.
Warnings
- gotcha The `lru_cache` decorator from `repoze.lru` explicitly does not support keyword arguments for decorated functions. All arguments must be positional.
- breaking Versions prior to 0.5 contained known thread safety issues and potential race conditions in `LRUCache.put()` and cache clearing logic. These could lead to incorrect cache state or performance degradation under concurrent access.
- gotcha Using `lru_cache` (or any `lru_cache` implementation) directly on instance methods of a class can lead to memory leaks. The cache will hold a strong reference to `self` (the instance) for each unique set of arguments, preventing instances from being garbage collected even after they are no longer actively used.
- gotcha The `repoze.lru` library officially supports Python 2.7 and Python 3.4+. While earlier Python 3 versions (e.g., 3.2) were mentioned in older documentation, relying on these for current development with version 0.7 might lead to unexpected issues.
Install
-
pip install repoze.lru
Imports
- LRUCache
from repoze.lru import LRUCache
- lru_cache
from repoze.lru import lru_cache
Quickstart
from repoze.lru import LRUCache, lru_cache
# Using LRUCache object
cache = LRUCache(100) # Max length of 100 items
cache.put('key1', 'value1')
print(f"Cache get 'key1': {cache.get('key1')}")
print(f"Cache get 'nonexisting' with default: {cache.get('nonexisting', 'default_value')}")
# Using lru_cache decorator
@lru_cache(50)
def expensive_function(arg1, arg2):
print(f"Executing expensive_function({arg1}, {arg2})")
return arg1 + arg2
print(f"Result 1: {expensive_function(1, 2)}") # Executes
print(f"Result 2: {expensive_function(1, 2)}") # Cached
print(f"Result 3: {expensive_function(3, 4)}") # Executes