I use __del__()
to write a warning log in case the object gets deleted while in a wrong internal state (please no wrath about it).
I tried to test it but although I use del my_object
in the test, the __del__()
doesn't seem to be called.
__del__()
's reference warns of 3 situations where this might happen, but doesn't give a clue on how to debug them.
So... How do I go about debugging it?
If __del__
is not being called when you invoke del myObject
directly, then there is at least one other outstanding reference to myObject. I'm guessing you have stuffed it into a list or dict or set (or perhaps a memoizing cache), which does not copy the object, just saves a second reference to the original. Even doing:
myObject = MyObjectClassWith__del__()
del myObject
might not necessarily call __del__
, if the class's __init__
method or __new__
method saves the new instance into some class-level cache or structure.
Bottom line: check for other references, either by inspecting your code, or by using the weakref or gc methods posted in other answers.