Python vs Java garbage collection?

Peter Hansen peter at engcorp.com
Mon Dec 23 19:58:48 EST 2002


Erik Max Francis wrote:
> 
> Robert Oschler wrote:
> 
> > Wait a minute, didn't Martin just say in a previous post that you can
> > rely
> > on CPython to call __del__ when reference counts reach 0?  How could
> > Python
> > "forget" to decrement a reference count, even if an exception occurs
> > in a
> > finally block or anywhere else for that matter?
> 
> Peter was giving an example where the reference count _didn't_ go to
> zero, but a naive programmer might not have noticed that.  It's yet
> another reason why explicit reclaiming of external resources is a good
> idea, even independently of this immediate vs. deferred finalization
> issue; it leaves open the opportunity for bugs.

That's what I intended.  As it turns out, on second examination and
a little experimentation, a call to flush() avoids the particular 
problem shown.

It doesn't entirely invalidates my argument, which Erik has captured above.
If you substitute the attempt to read from the file with a call to 
"os.remove('test.fil')", just for an example, the point remains.  

Calling .close() explicitly is a Good Idea, though there are cases 
where you don't really need to.  The number of such cases appears
to diminish as long as this thread continues...

I agree with the comment someone made about the source of much of the 
disagreement.  I personally don't use .close() explicitly much of the
time, but my lengthy programming experience and more recent maturation 
in that respect makes me feel a twinge of guilt every time I skip it.
It *is* sloppy, IMHO, and I *am* being lazy when I don't explicitly 
close my files, except perhaps in throw-away utilities or trivial programs
where the cost of not being lazy doesn't necessarily pay off.

In serious programs, even were it not for the existence of Jython, or
garbage collection that can't handle cycles with __del__ involved, it's
a good idea to be explicit, *especially* about resource management.

For my New Year's Resolution, I vow always to close my files explicitly
whenever I can, preferably with a tidy try/finally statement... :-)

-Peter



More information about the Python-list mailing list