__init__ vs. __del__

David Stanek dstanek at dstanek.com
Sun Mar 22 07:12:23 EDT 2009


2009/3/21 Randy Turner <rtmst3k at yahoo.com>:
> 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.
>

If you add a .close method to your class you can use
contextlib.closing[0]. I have used this to clean up distributed locks
and other non-collectable resources.

0. http://docs.python.org/library/contextlib.html#contextlib.closing

-- 
David
blog: http://www.traceback.org
twitter: http://twitter.com/dstanek



More information about the Python-list mailing list