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.

Easy Python 3.9+ Aug 9, 2026 Caching & Redis 13 views 0 copies

Python code

19 lines
Python 3.9+
from 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

stdout
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

  1. Use `cache.cache_clear()` on a functools.cache decorated function (Python 3.9+).
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Caching & Redis

Related tutorials and quizzes for this topic.