The problem
You need to cache expensive function calls with automatic expiration.
The solution
import functools
import time
from typing import Any, Callable
def ttl_cache(ttl_seconds: int = 300):
"""Cache decorator with time-to-live expiration."""
def decorator(func: Callable) -> Callable:
cache = {}
@functools.wraps(func)
def wrapper(*args, **kwargs) -> Any:
# Create cache key
key = (args, tuple(sorted(kwargs.items())))
# Check cache
if key in cache:
result, timestamp = cache[key]
if time.time() - timestamp < ttl_seconds:
return result
# Execute function and cache result
result = func(*args, **kwargs)
cache[key] = (result, time.time())
return result
return wrapper
return decoratorParameters
ttl_secondsintCache expiration time in seconds
Put it to work
@ttl_cache(ttl_seconds=60)
def expensive_api_call(user_id: int):
# Simulate API call
time.sleep(2)
return f"data_for_{user_id}"
# First call will execute, subsequent calls within 60s will use cache
result1 = expensive_api_call(123) # Takes 2 seconds
result2 = expensive_api_call(123) # Instant from cache