__init__ vs. __del__

Albert Hopkins marduk at letterboxes.org
Sat Mar 21 21:45:20 EDT 2009


On Sat, 2009-03-21 at 17:41 -0700, Randy Turner wrote:
> Hi,
> 
> 
> 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? 
> 


__del__ is called when the garbage collector is about to destroy an object.
There are times when it may not be called like IIRC when the interpreter exits
before an object is garbage collected or when there is an exception that causes
the object's reference count to stay >0, however...

In practice you rarely need to implement a __del__ method.  Memory is handled by the
garbage collector.  Most of the time you need not deal with it and in
the rare chance that you do there is a module to interface with the
interpreter's garbage collector.  File descriptors, network connections
and the like are usually handled either with an explicit .close() on the
object or by implementing/using context managers[1]. And of course if
you don't do so yourself then when the interpreter exits the OS closes
them implicitly.

1. http://docs.python.org/library/stdtypes.html#context-manager-types




More information about the Python-list mailing list