Python vs Java garbage collection?

François Pinard pinard at iro.umontreal.ca
Tue Dec 24 13:21:18 EST 2002


[Courageous]

> It's simply my gut feel and years of experience which say "closing
> explicitly is best practice."

Often, experience might come from languages other than Python.  We might be
careful when we extend our experience from one language to another, in
recognising the specificities of the new languages.  Our experience is often
helpful, but in some unusual cases, it may blinds us.

Even within Python (and I'm thinking CPython), experience taught me that
best practice is avoiding noisy code.  Explicitly closing a file which is
used very locally is similar to using `del' for variables we created through
assignment.  I have confidence in function exit cleanup for variables, and
whenever possible, I try to consider a file as just another type.

There _are_ cases when explicit closing a file is worth.  These are not so
frequent in practice: an explicit close warns our attention on an unusual
situation.  So you see, by not abusing of explicit closes, we even document
our code better, and increase its overall clarity.  Really, it's good style!

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard




More information about the Python-list mailing list