【发布时间】:2016-02-13 20:01:49
【问题描述】:
如何在类内部使用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()
但是foo 和foo.big(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(虽然可能会导致错误的结果)
【问题讨论】:
标签: python caching python-decorators lru functools