当前位置: 代码迷 >> python >> 如何在weakref.finalize中引用最终对象?
  详细解决方案

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

热度:107   发布时间:2023-07-16 10:15:01.0

我有一个不实现自己清理的类(我无法控制)。 我认为这是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引用finalized 对象是不可能的。 在 “注意”部分中,它说明了:

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

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