小编tel*_*tor的帖子

Python functools lru_cache与类方法:释放对象

如何在不泄漏内存的情况下在类中使用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的推荐方法是什么?

我知道两个解决方法: 使用每个实例缓存使缓存忽略对象(这可能会导致错误的结果)

python caching lru functools python-decorators

33
推荐指数
6
解决办法
9202
查看次数

标签 统计

caching ×1

functools ×1

lru ×1

python ×1

python-decorators ×1