我在python中有函数,它有lru_cache的缓存,例如
@lru_cache(maxsize=None)
def my_function():
...
虽然我可以单独清除缓存,例如my_function.cache_clear()
有没有办法一次清除每个函数的缓存? [我当时认为可能有一种方法可以返回内存中加载的所有函数名称,然后循环遍历它们清除每个函数的缓存]。
我特别希望实现作为后备的一部分,例如我机器上90%的内存被使用的情况。
答案 0 :(得分:2)
您可以创建一个修改后的装饰器,它也会记录缓存的函数:
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()
如果你真的想要你也可以使用猴子补丁来取代原来的装饰者。
测试:
@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()
输出:
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
答案 1 :(得分:2)
也许有一种方法可以返回所有功能 名称加载到内存中,然后循环清除缓存 来自每个
是的,这也是可能的:
import functools
import gc
gc.collect()
wrappers = [
a for a in gc.get_objects()
if isinstance(a, functools._lru_cache_wrapper)]
for wrapper in wrappers:
wrapper.cache_clear()
我特别希望实施作为后备的一部分,因为 假设我机器上90%的内存被使用的情况。
这是您在正常情况下可能不会使用的代码,但可用于调试。
在我的特定情况下,我想清除一些dangling file handles from matplotlib(为了专注于我自己的松散文件句柄),因此无法使用Alex Hall的解决方案。