file.close()

Paul Rubin http
Fri Jul 25 03:54:38 EDT 2003


Francois Pinard <pinard at iro.umontreal.ca> writes:
> For one, I systematically avoid cluttering my code with unneeded `close'.
> The advantages are simplicity and legibility, both utterly important to me.
> ...
> The only reason to call `close' explicitly is when there is a need to close
> prematurely.  Absolutely no doubt that such needs exist at times.  But
> closing all the time "just in case" is symptomatic of unsure programming.
> Or else, it is using Python while still thinking in other languages.

Unfortunately Python doesn't guarantee that you won't leak file
descriptors that way.  CPython happens to gc them when the last
reference disappears, and your willingness to patch the code if you
move to a different implementation may be workable for you (that's
something only you can decide).  But if you want to write correct code
in the current Python spec, you have to include those messy close's.

I think a much better solution would involve a language extension,
maybe a macro in some hypothetical macro extension for Python.  E.g.

    with f = open(frob):
      [do stuff with f]

could be equivalent to:

   f = open(frob)
   try:
     [do stuff with f]
   finally:
     f.done()                   # calls f.close()
     del f

"done" here is a generic method that gets called on exiting a "with"
block.  




More information about the Python-list mailing list