Problem

Using the del keyword on a Python object does not seem to really invoke the destructor

Solution

Q: After doing a del obj from a Python script where obj can be any Python object the destructor, __del__, of obj is never invoked.

Calling del on a Python object does not guarantee the destructor will be called! That simply decrements a counter internal to the object. It will invoke the destructor if (and only if) the internal counter, after it is decremented, has reached zero.

Q: Why doesn't the Python interpreter call the __del__ method of all Python objects contained within it before exiting?

There is not even a guarantee that the Python interpreter will invoke the destructors of all objects residing in it before exiting! This is part of the Python specification.

Workaround:

The only guaranteed way to ensure a destructor is called in Python is to call it in your own code like this:

obj.__del__()

Related articles

Related articles appear here based on the labels you select. Click to edit the macro and add or change labels.



Related issues