Expiring Dict

1.1.2 · active · verified Thu Apr 16

expiring-dict is a Python library that provides a dictionary-like object with Time-To-Live (TTL) support for its values, enabling automatic expiration of cached items. It is designed for simple caching scenarios where items need to be removed after a certain period. The library is currently active, with its latest version released in February 2025, and offers both dictionary-level and key-level expiration settings.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates creating an ExpiringDict with a global TTL and setting individual TTLs for specific keys. Accessing an expired key returns None, and the key is removed.

from expiring_dict import ExpiringDict
import time

# Dictionary-level TTL: items expire after 1 second
cache_dict_level = ExpiringDict(max_age_seconds=1)
cache_dict_level["my_key"] = "my_value"
print(f"Initial value (dict-level): {cache_dict_level.get('my_key')}")
time.sleep(1.5)
print(f"Value after 1.5 seconds (dict-level): {cache_dict_level.get('my_key')}") # Should be None

# Key-level TTL: individual keys expire after specified seconds
cache_key_level = ExpiringDict()
cache_key_level["persistent_key"] = "this never expires by default"
cache_key_level.ttl("expiring_key", "this expires in 1 second", 1)

print(f"\nPersistent value: {cache_key_level.get('persistent_key')}")
print(f"Expiring value (initial): {cache_key_level.get('expiring_key')}")
time.sleep(1.5)
print(f"Persistent value (after 1.5s): {cache_key_level.get('persistent_key')}")
print(f"Expiring value (after 1.5s): {cache_key_level.get('expiring_key')}") # Should be None

view raw JSON →