If you are wondering how to clear an LRU cache, the right method depends on where the cache is defined. In Python, the most common solution is to call cache_clear() on a function wrapped with functools.lru_cache. Other libraries and services use different APIs, and clearing a cache may remove entries only from the current process—or delete data shared across an entire application. This guide explains how to clear an LRU cache safely, check that it worked, and avoid common mistakes.
What Is an LRU Cache?
An LRU cache is a “least recently used” cache. It keeps recently accessed results so an application can reuse them instead of repeating expensive work. When the cache reaches its size limit, it typically removes the entry that has gone the longest without being used.
For example, a program might cache the result of a function that reads a file, performs a calculation, or looks up information. If the same input is requested again, the program can return the saved result quickly. This improves performance, but it also means the cached value can become outdated if the underlying data changes.
Clearing an LRU cache removes saved entries so future calls calculate or retrieve their results again. You might clear one when data changes, during testing, after a configuration update, or when you want to release memory.
How to Clear a Python LRU Cache
If you are using Python’s built-in functools.lru_cache, call cache_clear() on the decorated function. This removes all cached arguments and results for that function.
from functools import lru_cache
@lru_cache(maxsize=128)
def get_product(product_id):
print("Loading product...")
return {"id": product_id, "name": "Example"}
# Populate the cache
get_product(42)
# Remove every cached entry
get_product.cache_clear()
# The next call runs the function again
get_product(42)
The important detail is that cache_clear() belongs to the decorated function. You generally call it using the function’s name followed by the method, as in get_product.cache_clear(). You do not need to recreate the decorator or restart Python just to clear that function’s cache.
Calling cache_clear() does not change the function’s cache settings. If the function has maxsize=128, it will continue to allow up to 128 entries after the cache is cleared. The next function call can begin filling the cache again.
Clear the Cache from Another Function
You can clear an LRU cache anywhere in your program as long as you can access the decorated function. For example, an update operation can clear a cache after changing the data that the cached function reads.
from functools import lru_cache
@lru_cache(maxsize=256)
def get_settings():
return load_settings_from_disk()
def update_settings(new_settings):
save_settings_to_disk(new_settings)
get_settings.cache_clear()
In this example, clearing the cache prevents later calls to get_settings() from returning a saved result based on the previous settings. This is a useful pattern when cached results depend on data your application can modify.
For a larger application, consider keeping cache invalidation close to the code that updates the underlying data. If several functions cache related information, create a clearly named helper that clears each relevant cache. This makes it easier for other developers to understand when and why cached values are removed.
Check Whether an LRU Cache Was Cleared
Python’s functools.lru_cache provides cache_info(), which reports details about the cache. Its results include hits, misses, the maximum size, and the current number of cached entries.
print(get_product.cache_info())
# Example: CacheInfo(hits=1, misses=2, maxsize=128, currsize=2)
get_product.cache_clear()
print(get_product.cache_info())
# Example: CacheInfo(hits=0, misses=0, maxsize=128, currsize=0)
After clearing, currsize should be zero. The hit and miss counters are reset as well. This makes cache_info() useful when testing cache behavior or confirming that a reset happened. A subsequent call to the function will create a new entry if caching is enabled.
Clear an LRU Cache in a Class
If an LRU-cached function is defined inside a class, you can usually clear it through the method attribute. One detail matters: functools.lru_cache stores its cache on the wrapped function, not as a separate cache for every object instance.
from functools import lru_cache
class Catalog:
@lru_cache(maxsize=128)
def get_item(self, item_id):
return load_item(item_id)
# Clear the cache used by this method
Catalog.get_item.cache_clear()
Because the cache is associated with the method wrapper, clearing it this way clears cached calls across instances of Catalog. The instance, self, is part of the call’s arguments, so results for different instances are stored as different cache entries, but the entries still belong to the same wrapped method.
If you need each instance to manage its own cache independently, a function-level lru_cache may not be the best design. Consider using a per-instance cache or a caching library that supports the scope and invalidation behavior your application needs.
Clear an LRU Cache in Other Python Libraries
Not every Python LRU cache uses the same API. If you are using a third-party package, check its documentation for the cache’s specific clearing method.
-
cachetools: A cache object commonly supportsclear(). For example, callmy_cache.clear()to remove its entries. -
Framework caches: Django and other frameworks may provide cache interfaces with methods such as
clear()ordelete(). These may affect a shared backend rather than a single function. -
Custom LRU implementations: A project-specific cache might use a method named
clear,reset, orinvalidate. Confirm what the method removes before using it.
Do not assume that a method called clear() has the same scope everywhere. It might empty one object, a named cache region, a process-wide cache, or an external service. Check whether the cache is local or shared and whether the operation can affect other users or application components.
Clear a Redis Cache or Other Shared Cache
Redis and similar services are often used as shared application caches. They are not the same thing as a Python function’s functools.lru_cache. A shared cache may contain keys used by multiple servers, background jobs, or applications, so clearing it can have a much wider effect.
When possible, remove only the entries that are stale. If your application stores a result under a known key, delete that key using the cache client’s supported API. You can also use key prefixes, namespaces, or versioned keys to separate one application’s data from unrelated cache entries.
Commands that flush an entire Redis database can delete far more than one LRU cache. They may remove sessions, queues, or data used by other services. Avoid broad flush operations unless you have confirmed the target database, understand the impact, and have permission to clear it. For production systems, targeted invalidation is usually safer.
Does Restarting Python Clear an LRU Cache?
Usually, yes. A cache created by functools.lru_cache exists in memory inside the Python process. When that process stops, its in-memory cache disappears. Starting a new process creates a fresh cache.
However, restarting an application is not a universal cache-clearing method. A web application may run across several worker processes, and a restart might clear only the workers that were restarted. A Redis cache, database cache, or disk-based cache can also survive a Python process restart. Identify where the cache is stored before deciding how to clear it.
Common LRU Cache Clearing Mistakes
-
Calling the method on the wrong object: With
functools.lru_cache, calldecorated_function.cache_clear(), notcache_clear()by itself. - Clearing one cache but expecting another to change: Each decorated function has its own cache. Clearing one does not automatically clear every cache in your application.
- Expecting a cleared cache to stay empty: The next function call can immediately add a new entry.
- Assuming a process restart clears shared storage: External cache services can keep their data after the application restarts.
- Deleting too much: A global or database-wide clear can affect unrelated features. Prefer targeted invalidation when possible.
When Should You Clear an LRU Cache?
Clear a cache when its saved results are no longer valid or when you have a specific operational reason to remove them. Common situations include updating a configuration file, changing a record used by a cached lookup, running a test that requires a clean state, or recovering from unexpectedly stale results.
It is usually not necessary to clear an LRU cache simply because it exists. A size-limited cache automatically discards older entries as needed, and clearing it too often can reduce the performance benefit by forcing repeated work. If stale values are a recurring problem, review the cache’s lifetime, key design, and invalidation strategy instead of relying on manual resets.
Conclusion: The Fastest Way to Clear an LRU Cache
For a Python function decorated with functools.lru_cache, the fastest way to clear an LRU cache is to call your_function.cache_clear(). Use cache_info() to confirm that its current size is zero. For class methods, third-party libraries, framework caches, and Redis, use the clearing method that matches the cache’s scope and storage location.
Before clearing any cache, check whether it is local to one function or shared across processes and services. Targeted invalidation is often safer than removing everything, especially in production. With the correct method and scope, you can refresh outdated results without disrupting unrelated parts of your application.
Disclaimer: Articles are written by Humans, AI or Both. Verify Important information.