del behavior 2

Chris Rebert clp2 at rebertia.com
Wed Jan 7 14:57:00 EST 2009


On Wed, Jan 7, 2009 at 11:42 AM, Eric Snow <esnow at verio.net> wrote:
> I was reading in the documentation about __del__ and have a couple of
> questions.  Here is what I was looking at:
>
> http://docs.python.org/reference/datamodel.html#object.__del__
>
> My second question is about the following:
>
> "It is not guaranteed that __del__() methods are called for objects
> that still exist when the interpreter exits."
>
> I understand that and have seen it too.  That's fine.  But how do any
> of you deal with things that are left open because you did not get a
> chance to close them?  How do you clean up after the fact?  Do you
> simply keep track externally the things that need to be cleaned up if
> __del__ doesn't get a chance?  Any ideas?  Thanks

As you point out, __del__ is not a reliable way to free limited
resources. Instead, one generally includes logic to explicitly free
the resources. This is generally done using try-finally or the `with`
statement.

Example:

def mess_with_file(f):
    try:
        #fiddle with the file
    finally:
        f.close() #guarantee that the file gets closed

def mess_with_other_file(filename):
    with open(filename) as f:
        #do stuff with file
    x = None #the file has now been closed, and it'll be closed even
if an exception gets raised
    #the "context handler" (see PEP 343) for the `file` type
guarantees this for us

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list