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

How to reference finalized object in weakref.finalize?

我有一个 class(我不控制),它没有执行自己的清理。我认为这是 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))  

我是不是做错了什么?我误解了什么?

无法引用 weakref.finalize 中的最终对象。在 weakref.finalize 的 "Note" 部分中指出:

It is important to ensure that func, args and kwargs do not own any references to obj, either directly or indirectly, since otherwise obj will never be garbage collected. In particular, func should not be a bound method of obj.

因此,也不可能像weakref.finalize(obj, obj.close)那样用绑定方法来组织清理。在这种情况下,您需要自己调用清理功能。另一种选择是从 SomeClass 继承并制作适当的 __del__ 方法。