How to Invalidate a Cache in Python with lru_cache
This code demonstrates how to clear the cache of an @lru_cache decorated function in Python using cache_clear(), showing the effect on cached results.
Python code
19 linesfrom functools import lru_cache
import time
@lru_cache(maxsize=None)
def expensive_operation(key):
return f"Computed value for {key} at {time.time():.6f}"
def invalidate_cache():
expensive_operation.cache_clear()
if __name__ == "__main__":
print(expensive_operation("alpha"))
print(expensive_operation("beta"))
print(expensive_operation("alpha"))
invalidate_cache()
print(expensive_operation("alpha"))
print(expensive_operation.cache_info())
Output
Computed value for alpha at 1734567890.123456
Computed value for beta at 1734567890.234567
Computed value for alpha at 1734567890.123456
Computed value for alpha at 1734567890.345678
CacheInfo(hits=2, misses=3, maxsize=None, currsize=1)
How it works
The @lru_cache(maxsize=None) decorator caches the results of expensive_operation so repeated calls with the same argument return instantly. The first call with 'alpha' computes and stores the result; the second call with 'beta' computes and stores separately. Calling expensive_operation('alpha') again hits the cache and returns the exact same value (same timestamp). cache_clear() wipes the entire cache, forcing the next call to recompute, which produces a new timestamp. cache_info() returns a named tuple with hit/miss counters, maxsize, and current size — useful for monitoring cache effectiveness.
Common mistakes
- Calling cache_clear() on a non-decorated function, causing AttributeError.
- Forgetting that cache_clear() clears ALL entries, not just one key.
- Assuming cache_info() shows time values instead of hit/miss counts.
Variations
- Use `cache.cache_clear()` on a functools.cache decorated function (Python 3.9+).
- Use `cache_evict(key)` from a custom cache like `cachetools` to remove a single key.
Real-world use cases
- Invalidate cached database query results when an admin updates the underlying data.
- Force re-fetch of configuration values after a settings change without restarting the app.
- Clear sensitive cached data (e.g., user profiles) after a logout or permission change.
Sponsored
More from Caching & Redis
- Cache Asides in Python with a Read-Through Loader easy
- Cache Data in Redis with Python easy
- Cache Penetration Null Object Mock in Python medium
- Cache Stampede Prevention with SingleFlight in Python medium
- Cache Warming with Python: Preload Hot Keys easy
- Coalescing duplicate in-flight requests: one shared result for concurrent callers hard
Keep learning
Related tutorials and quizzes for this topic.