__init__ vs. __del__

Randy Turner rtmst3k at yahoo.com
Sat Mar 21 22:23:19 EDT 2009


There are a number of use-cases for object "cleanup" that are not covered by a generic garbage collector...

For instance, if an object is "caching" data that needs to be flushed to some persistent resource, then the GC has
no idea about this.

It seems to be that for complex objects, clients of these objects will need to explictly call the objects "cleanup" routine
in some type of "finally" clause, that is if the main "thread" of execution is some loop that can terminate either expectedly or
unexpectedly....

Relying on a generic GC is only for simple object cleanup...at least based on what I've read so far.

Someone mentioned a "context manager" earlier...I may see what this is about as well, since I'm new to the language.

Thanks!
Randy





________________________________
From: Albert Hopkins <marduk at letterboxes.org>
To: python-list at python.org
Sent: Saturday, March 21, 2009 6:45:20 PM
Subject: Re: __init__ vs. __del__

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

--
http://mail.python.org/mailman/listinfo/python-list



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090321/6373a833/attachment.html>


More information about the Python-list mailing list