to close or not to close?

Alex Martelli alex at magenta.com
Tue Aug 1 03:46:16 EDT 2000


"Grant Griffin" <g2 at seebelow.org> wrote in message
news:8m4s6i$2sdk at drn.newsguy.com...
> Hi Gang,
>
> Forgive me if this is a FAQ, but is it considered good Python form to
close a
> file whose variable is just about to go out of scope (and thus be
automatically
> closed)?  Or should one just omit that?

I think that depends on the programming culture one comes from.  People with
a C++ background are used to powerful idioms relying on destructors to free
all kinds of resources; people with a Java background are used to explicit
releasing (of non-memory resources), since finalize is not called reliably
(the
very explicit try/finally construct directly supports this style).  Other
languages
tend to fall into one or the other of these categories, too.

Python provides both reliably-called destructors (at least in CPython it
does;
the JPython or .NET dialects may work differently), _and_ try/finally, so
there
is really no 'pull' from the language itself towards one or the other idiom.


> tempted-to-omit-needless-code-ly y'rs,

Yes, that's a plus for the omission.  OTOH, 'explicit is better than
implicit', so
you can find Scripture to support the other stance, too.  I think both
styles are
quite defensible -- one avoids clutter, the other makes it easier to port to
JPython (if ever that should be needed) and may make it clearer to someone
reading the code which resource is released where (a readability plus, to
be,
however, offset against the readability cost that more clutter entails).

Me, I tend to rely on destructors, but that just goes to show that my main
relevant background is in C++...:-).


Alex






More information about the Python-list mailing list