Here is what the object.__del__(self)
documentation says:
Called when the instance is about to be destroyed
Here is what the del
documentation says:
Deletion of a name removes the binding of that name from the local or global namespace, depending on whether the name occurs in a global statement in the same code block
I've also read many related questions here on SO. I understood that if there are multiple variables pointing to the same object then of course deleting one name will not trigger the object __del__
method (because there is still a variable referencing the object).
So I tried a few experiments to check if I understood everything correctly. Let's say I have this class:
class A:
def __del__(self):
print('Object finalizer')
Now, this is what I have done:
>>> a1 = A()
>>> del a1
Object finalizer
Everything works as expected so far: there was only a single reference to that object, so once I delete that reference the object is also deleted. Then, I tried with two names referencing the same object:
>>> a1 = A()
>>> a2 = a1
Check that the two variables are actually referencing the same object:
>>> a1
<__main__.A object at 0x7fef201f4fd0>
>>> a2
<__main__.A object at 0x7fef201f4fd0>
But if I now try to delete all references, things do not go as expected:
>>> del a1
>>> del a2
>>>
I was expecting the __del__
method to be called after the del a2
statement. Why is this happening? What am I missing?