__init__ vs. __del__

Christian Heimes lists at cheimes.de
Sun Mar 22 02:37:38 CET 2009

Randy Turner wrote:
> I was reading a book on Python-3 programming recently and the book stated that, while there is an __init__ method for initializing objects, there was a __del__ method but the __del__ method is not guaranteed to be called when an object is destroyed.
> If there is code in the __init__ method that allocates resources (memory, file opens, etc.), how do these resources get cleaned up when an object is destroyed?  Custom method? 
> At the moment, this architecture seems a bit asymmetric if the __del__ method is not called.

The issue isn't as pressing as you may think. __init__() and __del__()
aren't the constructor and destructor of an object. They are the
initializer and finalizer of an object. The constructor is the __new__
function of a type. It's possible to construct an object without having
it's __init__() method called.

Since resources like memory, file handles and other stuff are usually
handled in C code, the type definition provides a rich set of API
methods. Objects that deal with resources like e.g. a database
connection are usually implemented in C, too. I suggest that you read up
the functions here:


__del__ is only problematic when the object is part of a reference
cycle. When the object isn't or can't be part of a cycle the __del__
method is called.

More information about the Python-list mailing list