expiringdict
expiringdict is a Python library that provides a dictionary-like object whose values automatically expire after a specified time-to-live (TTL). It's commonly used for caching purposes where stale data needs to be automatically removed. The current version is 1.2.2. The project appears to be stable with infrequent updates, indicating a maintenance phase rather than active feature development.
Warnings
- gotcha expiringdict is explicitly not thread-safe. Concurrent access from multiple threads without external locking will lead to unpredictable behavior and potential data corruption.
- gotcha Setting `max_age_seconds` to 0 does not mean items expire immediately; it means items will *never* expire based on age. Only `max_len` will trigger eviction.
- gotcha Iterating over an ExpiringDict while items are expiring (or being added/removed) can lead to a `RuntimeError` ('dictionary changed size during iteration') or inconsistent results, as the underlying dictionary is being modified.
Install
-
pip install expiringdict
Imports
- ExpiringDict
from expiringdict import ExpiringDict
Quickstart
from expiringdict import ExpiringDict
import time
# Create an expiring dictionary with max 100 items, and items expire after 2 seconds
cache = ExpiringDict(max_len=100, max_age_seconds=2)
print("Adding 'data' to cache...")
cache['my_key'] = 'data_value'
print(f"Retrieved immediately: {cache.get('my_key', 'Not found')}")
print("Waiting 3 seconds for expiration...")
time.sleep(3)
print(f"Retrieved after expiration: {cache.get('my_key', 'Not found')}")
# Direct access would raise KeyError: print(cache['my_key'])