gpt4 book ai didi

python - 在 Python 中清除所有 lru_cache

转载 作者:行者123 更新时间:2023-11-28 21:44:43 26 4
gpt4 key购买 nike

我在 python 中有一些函数,它们有 lru_cache 缓存,例如

 @lru_cache(maxsize=None)
def my_function():
...

虽然我可以单独清除缓存,例如my_function.cache_clear() 有什么方法可以一次清除每个函数的缓存吗? [我在想,也许有一种方法可以返回所有加载到内存中的函数名称,然后循环遍历它们,清除每个函数的缓存]。

我特别希望将实现作为回退的一部分,以应对我机器上 90% 的内存被使用的情况。

最佳答案

maybe there is a way of returning all function names loaded in memory, and then loop over them clearing the cache from each

是的,这也是可能的:

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()

I'm specifically looking to implement as part of a fall-back, for cases where say 90% of the memory on my machine gets used.

这是您在正常情况下可能不会使用的代码,但对调试很有用。

在我的特殊情况下,我想清除一些 dangling file handles from matplotlib (为了专注于我自己的松散文件句柄),所以无法使用 Alex Hall 的解决方案。

关于python - 在 Python 中清除所有 lru_cache,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40273767/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com