[Python-Dev] Smart resource destruction (was Re: Use for enumerate)

Guido van Rossum guido@python.org
Sun, 28 Apr 2002 09:14:53 -0400

> Look, if we're so careful about thread-naive code not crashing the
> interpretter (*) or circular references leaking memory (**), then I don't
> see why naive code should be allowed to leak file descriptors, database
> handles, query buffers, locks, or other similar things which:

Ian, why the speech?  If you leave the f.close() call out, it will
happen automatically.  In CPython, it happens automatically when the
refcount goes to 0, which (in this example) is when the function
returns.  In Jython, however, it would be when the garbage collector
feels like it, which may be too late in programs that open lots of
files -- and that's why we recommend as a general measure to
explicitly close files.

> *** .__class__ et. al. notwithstanding. The point is to avoid, for example,
> circular linked lists.

We're way ahead of you here, too.  Since Python 2.0, there's GC (in
addition to the refcounting) that clears up cycles. :)

--Guido van Rossum (home page: http://www.python.org/~guido/)