PYTHON
Implement LRU Cache with functools.lru_cache
Optimize Python functions with functools.lru_cache to store results of expensive calls, providing an efficient Least Recently Used (LRU) caching mechanism for web application performance.
import time
from functools import lru_cache
@lru_cache(maxsize=128) # Cache up to 128 results
def get_user_data(user_id):
"""
Simulates an expensive operation like a database query or API call.
"""
print(f"Fetching data for user_id: {user_id} (expensive operation)")
time.sleep(1) # Simulate delay
return {"id": user_id, "name": f"User {user_id}", "email": f"user{user_id}@example.com"}
print("First call for user 1:")
print(get_user_data(1)) # This will be expensive
print("
Second call for user 2:")
print(get_user_data(2)) # This will be expensive
print("
Third call for user 1 (cached):")
print(get_user_data(1)) # This will be fast, result from cache
print("
Fourth call for user 2 (cached):")
print(get_user_data(2)) # This will be fast, result from cache
# Demonstrate cache info
print(f"
Cache Info: {get_user_data.cache_info()}")
# Example Output: Cache Info: CachesInfo(hits=2, misses=2, maxsize=128, currsize=2)
How it works: The `@lru_cache` decorator from the `functools` module provides an easy way to cache the results of function calls. When the decorated function is called with the same arguments, it returns the cached result instead of executing the function body, significantly improving performance for idempotent (side-effect free) functions that might involve expensive database queries or API calls. `maxsize` limits the cache size, automatically evicting the least recently used items when full, making it a valuable tool for backend optimization.