PYTHON

Implementing LRU Cache for Function Results with functools.lru_cache

Optimize expensive function calls in your Python web applications using `functools.lru_cache` to store and retrieve previously computed results, improving performance significantly.

import functools
import time

@functools.lru_cache(maxsize=128)
def fetch_user_data(user_id: int) -> dict:
    """Simulates an expensive database or API call."""
    print(f"Fetching data for user_id: {user_id}...")
    time.sleep(1) # Simulate delay
    return {"id": user_id, "name": f"User {user_id}", "email": f"user{user_id}@example.com"}

print("First call:")
print(fetch_user_data(1))
print(fetch_user_data(2))
print(fetch_user_data(1)) # This call will be cached

print("
Second set of calls (demonstrating cache hit):")
print(fetch_user_data(3))
print(fetch_user_data(2)) # This call will be cached
How it works: The `functools.lru_cache` decorator is a powerful way to memoize (cache) the results of a function. It stores the results of function calls and returns the cached result if the same arguments are passed again, avoiding re-computation. This is invaluable for optimizing functions that involve expensive I/O operations (like database queries or API calls) in web applications, significantly improving response times. `maxsize` controls how many results are stored (Least Recently Used items are discarded first).

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs