The documentation states:
The decorator also provides afunction for clearing or
invalidating the cache.
lru_cache decorator also adds new functions, to the decorated function -
cache_clear. Below is a simple example that should explain how they work:
>>> @lru_cache(5) ... def foo(): ... print('Executing foo...') ... >>> foo() Executing foo... >>> foo() >>> foo.cache_info() CacheInfo(hits=1, misses=1, maxsize=5, currsize=1) >>> foo.cache_clear() >>> foo() Executing foo...
Answering your questions:
If I put a cache_clear() call conditionally inside the function that is being cached, will it ever get executed?
If the result is not cached already, the function will execute and based on your conditions, it should execute
cache_clear. I wouldn't use such solution though - a good practise is to invalidate outside the cached object, otherwise you risk no invalidation at all in worst cases, unreadable code in best case.
How can I run cache_clear() from a different function?
Just import cached function and call
cache_clear on it:
from x import foo def bar(): foo.cache_clear()