functools.lru_cache with TTL support and async compatibility — a single decorator for both sync and async functions.
pip install ttlru
from ttlru import ttl_cache
# Works for both sync and async — TTL=-1 means never expire (default)
@ttl_cache(ttlru_ttl=60, ttlru_maxsize=256)
def fetch_user(user_id: int):
...
@ttl_cache(ttlru_ttl=30)
async def fetch_remote(url: str):
...
# No parens — uses defaults (no expiry, maxsize=128)
@ttl_cache
def compute(x):
...
# Cache management (mirrors functools.lru_cache)
fetch_user.cache_clear()
fetch_user.cache_info() # CacheInfo(hits=…, misses=…, maxsize=…, currsize=…)All decorator keyword arguments use the ttlru_ prefix so they never clash
with parameters of the decorated function (e.g. a function that has its own
ttl or config parameter).
| Parameter | Default | Description |
|---|---|---|
ttlru_ttl |
-1 |
Seconds before entry expires. -1 = never expire. |
ttlru_maxsize |
128 |
Max entries. None = unlimited, 0 = no caching. |
ttlru_typed |
False |
Cache f(3) and f(3.0) separately when True. |
ttlru_config |
global | CacheConfig instance for enabled flag and telemetry. |
from ttlru import set_telemetry_provider, MetricsTelemetryProvider
set_telemetry_provider(MetricsTelemetryProvider(my_otel_counter))Built-in providers: LoggingTelemetryProvider (default, DEBUG level), MetricsTelemetryProvider, NoOpTelemetryProvider.