我有一个类(我不控制)没有实现自己的清理。我认为这是 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 的“注意”部分据称:
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) 这样的绑定(bind)方法来组织清理。在这种情况下,您需要自己调用清理功能。另一种选择是从 SomeClass 继承并创建适当的 __del__ 方法。
