Why no open(f, "w").write()?

John La Rooy larooy at xtar.co.nz
Sat Jun 1 05:44:04 CEST 2002

On 30 May 2002 10:10:52 -0400
pinard at iro.umontreal.ca (François Pinard) wrote:

> [Delaney, Timothy]
> > Why don't we have
> > 	while a = file.readline():
> > 	    pass
> > while we're at it?  After all, it's the same principle - you're trading
> > off safety for saving a line or two.
> The Python language is oriented towards legibility and clarity, and I
> would guess that the above has been rejected as lacking legibility, much
> more than for safety considerations.
> Doing `lines = open(file).readlines()' looks perfectly safe to me, so I'm
> not trading any safety.  The goal of using such writing is not "saving a
> line or two", but writing more legibly, by eliminating unnecessary noise.
> Saving lines is not very important.  Saving spurious lines is, however.
> All those things are quite debatable, there is some aesthetic considerations
> associated with legibility; moreover, aesthetics do not alway yield to
> legibility.  I think Python is nice because it has _one_ artist in charge,
> able to impose a common view.  If it was "democratic", it would loose much.
> -- 
> François Pinard   http://www.iro.umontreal.ca/~pinard

And certainly if something looks safe, ideally it should be so. Why do we close
files at all ever? Explicitly closing a file *should* be as rare as explicitly
deleting a variable. The reason we do it is because we *know* something about
the underlying implementation i.e. that files are buffered. I hope that CPython
is never going to change that behaviour of closing the file for me when refcount=0
and I think the Jython developers should consider a mechanism for doing it too.

When refcount gets down to 0 and we make an object available for GC can't we ask
is it a file? If so we better flush and close it?

One of the reasons Python is quick to develop in is that we don't have to worry
about memory management much (but we can if we need to). Likewise the less I have
 to deal with the fact that some I/O is buffered in my day to day work the better
 (as long as I can if I need to).


More information about the Python-list mailing list