How to debug uncalled __del__()
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 abou开发者_C百科t 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.
You can change all references between the suspect objects to weakref and watch the output of the callback you provide to weakref.ref
Well, you can try to force gc to collect the object. If you want to find out what objects still have references to your objects and might be keeping them from being garbage collected, play around with gc.get_referrers
and gc.get_referents
.
精彩评论