Skip to content

TTL Cache

PyPI - Version PyPI - Python Version CI codecov Docs

An LRU cache decorator with a time to live. ttl_lru_cache works exactly like functools.lru_cache, except entries automatically expire after a configurable number of seconds.

Basic usage
from ttl_cache import ttl_lru_cache


@ttl_lru_cache(ttl=30)  # (1)!
def fetch_user(user_id: int) -> dict:
    print("Fetching from the network...")
    return {"id": user_id, "name": "Ada"}


fetch_user(1)  # Prints "Fetching from the network..."
fetch_user(1)  # Cache hit, nothing printed
# ... 30 seconds later ...
fetch_user(1)  # Expired — fetches again
  1. Cache results for 30 seconds. While the TTL window is open, repeat calls with the same arguments are served from the cache.