如何在不泄漏内存的情况下在类中使用functools的lru_cache?在下面的最小示例中,foo虽然超出范围且没有引用者(lru_cache除外),但实例不会被释放.
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()
Run Code Online (Sandbox Code Playgroud)
但是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
Run Code Online (Sandbox Code Playgroud)
这意味着Foo/BigClass实例仍然驻留在内存中.即使删除Foo(del Foo)也不会释放它们.
为什么lru_cache会依赖实例?缓存不是使用一些哈希而不是实际对象吗?
在类中使用lru_caches的推荐方法是什么?