Thread-safe TTL cache decorator
Python
import functools
import threading
import time
def ttl_cache(seconds: float):
"""Memoise a function for `seconds`, refreshing the value on expiry."""
def decorator(func):
store: dict[tuple, tuple[float, object]] = {}
lock = threading.Lock()
@functools.wraps(func)
def wrapper(*args, **kwargs):
key = (args, tuple(sorted(kwargs.items())))
now = time.monotonic()
with lock:
hit = store.get(key)
if hit is not None and hit[0] > now:
return hit[1]
value = func(*args, **kwargs)
with lock:
store[key] = (time.monotonic() + seconds, value)
return value
return wrapper
return decorator
@ttl_cache(seconds=30)
def load_settings(path: str) -> dict:
print(f"loading {path}")
return {"path": path}
if __name__ == "__main__":
load_settings("app.toml")
load_settings("app.toml") # served from cache, so no second print