PythonmediumPython

TTL Cache Decorator

Function caching with time-to-live (TTL) expiration.

01

The problem

You need to cache expensive function calls with automatic expiration.

02

The solution

Python
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 decorator

03

Parameters

ttl_secondsint

Cache expiration time in seconds

04

Put it to work

Example
@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