Thread-safe LRU cache decorator with optional TTL expiration.
pip install lru_cachefrom lru_cache import LruCache
@LruCache(maxsize=128, timeout=300)
def get_user(user_id: int) -> dict:
# expensive operation
return fetch_from_db(user_id)
# Invalidate a specific entry
get_user.invalidate(42)
# Clear all cached entries
get_user.cache_clear()
# Inspect cache state
get_user.cache_info() # {'size': 10, 'maxsize': 128, 'timeout': 300}| Parameter | Type | Default | Description |
|---|---|---|---|
maxsize |
int | None |
None |
Maximum number of cached entries. None = unbounded. |
timeout |
float | None |
None |
TTL in seconds. None = entries never expire. |
- Thread-safe: all operations protected by
RLock - TTL support: entries auto-expire after
timeoutseconds using monotonic clock - LRU eviction: least-recently-used entries evicted when
maxsizeis reached - Typed: full type annotations with
py.typedmarker (PEP 561) - Zero dependencies: pure Python, no external packages
The import path changed to fix a namespace collision (#4):
# Old (0.x)
from cache import LruCache
# New (1.x)
from lru_cache import LruCacheMIT