If a Python function decorated with @lru_cache keeps returning an old result, clearing its cache is usually straightforward. The standard library’s functools.lru_cache adds a cache_clear() method to the decorated function, letting you remove every cached entry without changing the function’s code. This guide explains how to clear an LRU cache in Python, when to do it, how to check cache usage, and what to consider when you need to remove just one result.
What Is an LRU Cache in Python?
An LRU cache stores results from previous function calls so Python can return a saved result instead of calculating it again. “LRU” means “least recently used”: when a bounded cache reaches its maximum size, it discards the entry that has gone unused for the longest time.
Python provides LRU caching through functools.lru_cache. You apply it as a decorator to a function, optionally setting a maximum number of entries with maxsize.
from functools import lru_cache
@lru_cache(maxsize=128)
def get_value(number):
print("Calculating...")
return number * number
print(get_value(5)) # Calculates and returns 25
print(get_value(5)) # Returns cached 25
For a cache to work, the function’s arguments must be hashable, and the function should generally return the same result for the same arguments. If the result depends on changing external data, such as a file, database, or configuration value, a cached result may become outdated. Clearing the cache lets the function calculate fresh results.
How to Clear an LRU Cache in Python
Call cache_clear() on the decorated function. It removes all entries from that function’s cache:
get_value.cache_clear()
After the call, the next invocation for any argument will run the original function again. Here is a complete example:
from functools import lru_cache
@lru_cache(maxsize=128)
def get_price(product_id):
print(f"Loading price for product {product_id}")
return product_id * 10
get_price(7) # Prints the loading message; returns 70
get_price(7) # Uses the cached result
get_price.cache_clear()
get_price(7) # Prints the loading message again
The cache_clear() method takes no arguments. It clears the entire cache associated with that decorated function, not just the entry for a particular argument. It also resets the cache’s hit and miss statistics.
Clear the Cache When Underlying Data Changes
A common reason to clear an LRU cache is that its source data has changed. For example, suppose a function reads a setting from a file and caches the result. If the file is updated, the function may continue returning the old setting until its cache entry is removed or the entire cache is cleared.
from functools import lru_cache
@lru_cache(maxsize=1)
def load_setting():
with open("settings.txt", encoding="utf-8") as file:
return file.read().strip()
setting = load_setting()
# After settings.txt changes:
load_setting.cache_clear()
setting = load_setting() # Reads the updated file
This pattern can also be useful after updating database records, refreshing configuration, changing application state, or completing a test that relies on cached results. Clear the cache at the point where the underlying data changes, or provide a deliberate refresh function that performs the update and then clears the cache.
Check Cache Statistics Before and After Clearing
Python’s LRU cache wrapper provides cache_info(), which reports how the cache is being used. Its result includes the number of hits, misses, the maximum size, and the current number of entries.
print(get_price.cache_info())
# Example: CacheInfo(hits=1, misses=1, maxsize=128, currsize=1)
get_price.cache_clear()
print(get_price.cache_info())
# Example: CacheInfo(hits=0, misses=0, maxsize=128, currsize=0)
This is useful when troubleshooting performance or confirming that a cache was cleared. A hit means Python found a result in the cache; a miss means it had to call the original function. The currsize value shows how many entries are currently stored.
Clear an LRU Cache in Tests
Caches can make tests order-dependent. If one test populates a cache, a later test might receive a saved result rather than exercising the function as intended. Clear the cache between tests to start each test with a clean state.
def test_first_case():
get_price.cache_clear()
assert get_price(3) == 30
def test_second_case():
get_price.cache_clear()
assert get_price(4) == 40
With pytest, a fixture can clear the cache before and after each test:
import pytest
@pytest.fixture(autouse=True)
def clear_price_cache():
get_price.cache_clear()
yield
get_price.cache_clear()
Use this approach when tests share the same decorated function and cached values could affect their results. If several functions are cached, clear each relevant wrapper or create a test helper that resets all of them.
Can You Clear Only One Cached Entry?
The built-in functools.lru_cache does not provide a public method for deleting a single entry by its arguments. Calling cache_clear() removes every cached entry for the decorated function. If you need to invalidate only one result, consider these options:
- Clear the whole cache. This is the simplest choice when the cache is small or recalculating results is inexpensive.
- Add a version or timestamp argument. When the version changes, calls use a new cache key, so outdated entries are no longer selected. Old entries remain until eviction or a full clear.
- Use a custom cache. A dictionary or dedicated caching library may be a better fit when individual keys must be deleted or given different expiration rules.
A version argument can be useful when the cached calculation depends on a data source that has a revision number:
from functools import lru_cache
@lru_cache(maxsize=128)
def get_record(record_id, data_version):
return load_record_from_source(record_id)
current_version = 1
record = get_record(42, current_version)
# After the source changes:
current_version += 1
record = get_record(42, current_version)
Because data_version is part of the cache key, the updated call does not reuse the result stored under the previous version. This approach does not physically delete the old entry immediately, so a full cache clear may still be appropriate when memory use matters.
Clearing Caches on Class Methods
You can decorate a method with @lru_cache, but the instance, represented by self, becomes part of the cache key. Calling the cache-clearing method through the class-level function clears the shared wrapper’s cache, including entries for all instances.
from functools import lru_cache
class Catalog:
@lru_cache(maxsize=128)
def get_item(self, item_id):
return load_item(item_id)
# Clear cached method results for all Catalog instances:
Catalog.get_item.cache_clear()
Be thoughtful when caching methods on objects that are created and discarded frequently. The cache can retain references to arguments, including instances, until entries are evicted or the cache is cleared. If you need caching that is limited to each object’s lifetime, another caching design may be more suitable.
Clearing an Unbounded Cache with functools.cache
Python also provides functools.cache, an unbounded caching decorator available in Python 3.9 and later. It is equivalent to using lru_cache(maxsize=None): entries are not removed based on a maximum size. Its wrapper also supports cache_clear().
from functools import cache
@cache
def calculate(number):
return number ** 3
calculate(4)
calculate.cache_clear()
Since an unbounded cache can keep accumulating entries, clear it when appropriate or choose lru_cache with a maximum size if you need a limit. Clearing an unbounded cache removes all saved results just as it does with a bounded LRU cache.
Common Mistakes to Avoid
-
Calling
cache_clear()on the wrong object. It belongs to the decorated function, not the original undecorated function or thelru_cachemodule. - Expecting to remove one key. The built-in method clears the full cache; it does not accept arguments.
- Assuming the cache clears automatically when data changes. Python does not know that a database row, file, or global setting has changed.
- Using cached functions with changing side effects. Caching is best for repeatable calculations. A function that is expected to perform an action on every call may not be a good candidate.
- Forgetting that method caches are shared by the wrapper. Clearing a decorated method’s cache through the class clears entries across instances.
Threaded programs can use the cache safely in the sense that its internal data structure remains coherent. However, simultaneous calls for the same uncached arguments may still cause the underlying function to run more than once. Cache clearing should not be treated as a guarantee that no in-progress computation can finish or repopulate the cache afterward.
Conclusion
To clear an LRU cache in Python, call your_function.cache_clear() on the function decorated with @lru_cache. This removes all of that function’s cached results and resets its usage statistics. Use it after source data changes, between tests, or whenever saved results should no longer be reused. If you need selective invalidation, the built-in cache does not support deleting a single entry, so consider versioned cache keys or a custom caching solution.
Disclaimer: Articles are written by Humans, AI or Both. Verify Important information.