del behavior 2

Chris Rebert clp2 at
Wed Jan 7 20:57:00 CET 2009

On Wed, Jan 7, 2009 at 11:42 AM, Eric Snow <esnow at> wrote:
> I was reading in the documentation about __del__ and have a couple of
> questions.  Here is what I was looking at:
> 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`


def mess_with_file(f):
        #fiddle with the file
        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


Follow the path of the Iguana...

More information about the Python-list mailing list