I have a class (that I do not control) that doesn't implement its own cleanup. I thought that this is one of the cases that weakref.finalize
is for, but I can't get it working.
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))
Am I doing something wrong? What have I misunderstood?