Should I close after popen??

David Bolen db3l at fitlinxx.com
Fri Mar 30 13:03:59 EST 2001


pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) writes:

> Explicit closing is probably not always good practice, and is not necessarily
> safer.  I would completely agree with the above for someone who wants to
> write Jython, or write Python that could be quickly turned into Jython.
> But if you stick with Python, you can safely rely on the fact that a file
> is automagically close as soon as you do not refer to it anymore.

I'd probably change Python in that sentence to CPython, since it's an
implementation issue and not a language one (the language makes no
such guarantees).

> In fact, if I remember well, Tim Peters confirmed (on this list) that
> Python, the C implementation, is very not likely to change on this.
> 
> Code like:
> 
>     open(logfile, 'a').write('Done!\n')
> 
> or maybe:
> 
>     for line in open(logfile).readlines():
>         process(line)
> 
> is very legible, and would rather be uselessly encumbered with explicit
> closes and intermediate variables.  It is not worth writing these in the
> style of other languages where closes are explicitely needed.

I can agree on the second point, but would caution that on the first
point you have no guarantees that your data actually got to the
logfile without doing the close and possibly handling any errors
there.

Ok, you may say the odds of failure are low and depending on the
criticality of the data it may or may not matter, but it's all too
easy to forget that there's any risk at all when looking at the code,
so I think it bears repeating in these sorts of discussions.

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list