to close or not to close?

François Pinard pinard at iro.umontreal.ca
Mon Jul 31 20:08:59 EDT 2000


[Thomas Wouters]

> On Mon, Jul 31, 2000 at 02:48:02PM -0700, Grant Griffin wrote:

> > 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 came to consider it is a better form to _not_ close explicitely.  Cases
where explicit close is really useful are rather unusual, in my experience.
In which cases, an explicit `close' gets more meaningful, and less noisy.
And even then, I much prefer `file = None' than `close(file)', because the
former really represents my intent: I promise I will not use `file' anymore.
I like to think that closing a file is a system concern, not a user concern.

> In current CPython it won't cause any problem to omit the close as long as
> you are certain the vrbl will go out of scope, but JPython and possibly
> other implementations of Python use true garbage collection (GC) rather
> than reference counting (RC).

This is true, and this is partly why I consider that CPython allows for
less cluttered coding in such areas.  I'm well prepared to revise my code
if I ever need to use JPython.  But until I do, I prefer clean and clear.

> for x in [:256]: # or range(256) if you don't run experimental patches
> 	open("tempfile.%d"%x)

> Will work just fine in CPython, having open at most 2 'tempfiles' at once
> (in an interactive session, that is, otherwise it has just 1 open.)

I do not understand how we could have two.  Since the result of `open'
is not saved, I presume the file will be closed immediately after being
opened, before executing the next instruction, or the next iteration.

> But the same script under JPython, or a possible future CPython with true
> GC, will run out of filedescriptors (or more likely: the max number of
> open files) before the next GC run.

On this list, I got a kind of guarantee that future CPython will stick
with reference counting, possibly _complemented_ by more traditional mark
and sweep.  So, any current clean code will continue to work.

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




More information about the Python-list mailing list