Python functools.lru_cache Not Caching Fix
In this tutorial, you'll learn about Python functools.lru_cache Not Caching Fix. We cover key concepts, practical examples, and best practices.
Python's functools.lru_cache stores return values of pure functions to avoid recomputation. When caching appears broken, the cause is usually unhashable arguments, mutable default values, or functions with side effects that confuse the cache key.
The Wrong Way
from functools import lru_cache
@lru_cache(maxsize=128)
def get_data(items):
return sorted(items)
result1 = get_data([3, 1, 2])
result2 = get_data([3, 1, 2]) # Cache miss every time
print(result1)
print(result2)
Output:
[1, 2, 3]
[1, 2, 3]
Each call produces a cache miss because lists are unhashable, so lru_cache cannot store or look up the result.
The Right Way
Use hashable arguments like tuples:
from functools import lru_cache
@lru_cache(maxsize=128)
def get_data(items):
return sorted(items)
result1 = get_data((3, 1, 2))
result2 = get_data((3, 1, 2))
print(f"Cache info: {get_data.cache_info()}")
Output:
Cache info: CacheInfo(hits=1, misses=1, maxsize=128, currsize=1)
Step-by-Step Fix
1. Use hashable argument types
@lru_cache
def process(items_tuple):
return sum(items_tuple)
process((1, 2, 3)) # Tuple is hashable
2. Handle unhashable args by converting them
@lru_cache
def fetch_user(user_id, config_frozen):
config = dict(config_frozen) # Thaw for use
return f"User {user_id} with config {config}"
config = frozenset({"theme": "dark", "lang": "en"}.items())
fetch_user(1, config)
3. Remove mutable defaults from cached functions
@lru_cache
def compute(x, cache=None):
if cache is None:
cache = {}
cache[x] = x * x
return cache
4. Avoid side-effect-dependent functions
import time
from functools import lru_cache
@lru_cache
def expensive(n):
return n * n
# Functions that depend on time or global state cannot be effectively cached
def time_dependent():
return int(time.time()) // 60 # Changes every minute
5. Clear the cache when needed
@lru_cache
def get_config(key):
return f"value_{key}"
get_config("host")
get_config.cache_clear()
get_config("host") # Cache miss again
Prevention Tips
- Use hashable types (tuple, str, int, frozenset) as arguments to cached functions.
- Turn lists into tuples and dicts into frozensets before passing to cached functions.
- Keep cached functions pure -- no side effects or dependencies on mutable global state.
- Avoid mutable default arguments in cached functions.
- Use
cache_clear()andcache_info()to monitor and manage caching behavior.
Common Mistakes with functools lru
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro