PYTHON
Optimizing Function Calls with `functools.lru_cache`
Boost web application performance by memoizing expensive function calls using Python's `functools.lru_cache`, effectively caching results and reducing redundant computations.
import time
from functools import lru_cache
# Maxsize defines how many recent calls to store.
# Set to None for an unbounded cache (use with caution for memory).
@lru_cache(maxsize=128)
def fetch_data_from_api(item_id):
"""
Simulates an expensive API call to fetch data for a given item ID.
Results are cached based on item_id.
"""
print(f"Fetching data for item_id: {item_id} (simulated API call)...")
time.sleep(1) # Simulate network latency or heavy computation
return {"id": item_id, "name": f"Item {item_id} Data", "timestamp": time.time()}
# Example Usage:
print("First call for item 1:")
data1 = fetch_data_from_api(1)
print(f"Result 1: {data1}")
print("
Second call for item 2:")
data2 = fetch_data_from_api(2)
print(f"Result 2: {data2}")
print("
Third call for item 1 (should be cached):")
data1_cached = fetch_data_from_api(1) # This should be faster
print(f"Result 1 (cached): {data1_cached}")
print("
Fourth call for item 3:")
data3 = fetch_data_from_api(3)
print(f"Result 3: {data3}")
# Check cache statistics
print(f"
Cache statistics: {fetch_data_from_api.cache_info()}")
How it works: This snippet demonstrates `functools.lru_cache`, a powerful decorator for memoizing function results, which is internally backed by a dictionary-like data structure. When `fetch_data_from_api` is called with a specific `item_id`, `lru_cache` stores its return value. Subsequent calls with the same `item_id` will return the cached result immediately, avoiding the expensive "API call" (simulated by `time.sleep`). This is invaluable for optimizing web applications by reducing redundant computations, database queries, or external API calls, significantly improving response times for frequently requested data. `maxsize` controls the cache capacity, evicting the least recently used items when full.