如何在不泄漏内存的情况下在类中使用functools的lru_cache?在下面的最小示例中,尽管超出了作用域并且没有referrer (除了lru_cache之外),foo
实例也不会被释放。
from functools import lru_cache
class BigClass:
pass
class Foo:
def __init__(self):
self.big = BigClass()
@lru_cache(maxsize=16)
def cached_method(self, x):
return x + 5
def fun():
foo = Foo()
print(foo.cached_method(10))
print(foo.cached_method(10)) # use cache
return 'something'
fun()
但是foo
和foo.big
(a BigClass
)仍然活着
import gc; gc.collect() # collect garbage
len([obj for obj in gc.get_objects() if isinstance(obj, Foo)]) # is 1
这意味着Foo/BigClass实例仍然驻留在内存中。即使删除Foo
(del Foo
)也不会释放它们。
为什么lru_cache要保留这个实例?缓存不是使用了一些散列而不是实际的对象吗?
在类中使用lru_caches的推荐方式是什么?
我知道有两种变通方法:Use per instance caches或make the cache ignore object (但这可能会导致错误的结果)
https://stackoverflow.com/questions/33672412
复制相似问题