You can create a modified decorator which also takes note of the cached functions:
cached_functions = []
def clearable_lru_cache(*args, **kwargs):
def decorator(func):
func = lru_cache(*args, **kwargs)(func)
cached_functions.append(func)
return func
return decorator
def clear_all_cached_functions():
for func in cached_functions:
func.cache_clear()
If you really want you can also use monkey patching to replace the original decorator.
Test:
@clearable_lru_cache()
def foo(x):
print('foo', x)
@clearable_lru_cache()
def bar(x):
print('bar', x)
for i in [1, 2]:
for j in [1, 2]:
print('Calling functions')
for k in [1, 2, 3]:
for f in [foo, bar]:
f(k)
print('Functions called - if you saw nothing they were cached')
print('Clearing cache')
clear_all_cached_functions()
Output:
Calling functions
foo 1
bar 1
foo 2
bar 2
foo 3
bar 3
Functions called - if you saw nothing they were cached
Calling functions
Functions called - if you saw nothing they were cached
Clearing cache
Calling functions
foo 1
bar 1
foo 2
bar 2
foo 3
bar 3
Functions called - if you saw nothing they were cached
Calling functions
Functions called - if you saw nothing they were cached
Clearing cache
my_function.cache_clear()
. You can also get stats withmy_function.cache_info()
. Seelru_cache
– Vins