我在python中有带有lru_cache缓存的函数。
@lru_cache(maxsize=None)
def my_function():
...虽然我可以使用例如my_function.cache_clear()单独清除缓存,但有什么方法可以同时清除每个函数的缓存吗?我在想,也许有一种方法可以返回加载在内存中的所有函数名,然后循环遍历它们,从每个函数中清除缓存。
我特别希望将其实现为回落的一部分,比如我机器上90%的内存都被使用了。
发布于 2016-10-27 00:42:18
您可以创建一个修改后的装饰器,它还注意到缓存的函数:
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发布于 2018-06-05 11:40:59
也许有一种方法可以返回加载在内存中的所有函数名,然后循环它们从每个函数中清除缓存。
是的,这也是可能的:
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%的内存都被使用了。
这是您可能不会在正常情况下使用的代码,但对于调试可能很有用。
在我的特殊情况下,我想清除一些从matplotlib悬空文件句柄 (为了关注我自己的松散文件句柄),所以不可能使用Alex的解决方案。
https://stackoverflow.com/questions/40273767
复制相似问题