如何在weakref.finalize中引用最终确定的对象?

问题描述 投票:2回答:1

我有一个我不控制的类,它没有实现自己的清理。我以为这是weakref.finalize适用的情况之一,但我无法使其正常工作。

def cleanup(obj):
    print('Cleanup obj')
    if not obj.is_closed:
        obj.close()
...

def make_obj():
    obj = SomeClass()

    # this creates an extra ref, so cleanup is never run
    weakref.finalize(obj, cleanup, obj)

    # this always results in ReferenceError; obj is already gone when cleanup is called
    weakref.finalize(obj, cleanup, weakref.proxy(obj))  

我做错什么了吗?我误解了什么?

python python-3.6 weak-references
1个回答
0
投票

无法引用weakref.finalize中的最终对象。在weakref.finalize的“注释”部分中指出:

重要的是要确保func,args和kwargs不拥有任何直接或间接引用obj,否则obj永远不会被垃圾收集。特别地,func不应该是obj的绑定方法。

因此,也无法使用weakref.finalize之类的绑定方法来进行清理。在这种情况下,您需要自己调用清理函数。另一种选择是从weakref.finalize(obj, obj.close)继承并制定适当的SomeClass方法。

© www.soinside.com 2019 - 2024. All rights reserved.