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

Sto*_*ica 7 python weak-references

我有一个类(我无法控制)没有实现自己的清理。我认为这是其中一种情况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))  
Run Code Online (Sandbox Code Playgroud)

难道我做错了什么?我误解了什么?

san*_*ash 6

不可能在 中引用最终对象weakref.finalize。在“注意”部分中weakref.finalize指出:

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

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