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

Petr Prikryl Answer.via.news.please.prikrylp at nospam_skil.cz
Thu May 30 03:13:24 EDT 2002


"François Pinard"  wrote...
> [Gary Herron]
>
> > Thus the "bad" part of this programming practice is that the timing
> > of the implied close is dependent Python implementation issues (i.e.,
> > the timing of the garbage collection), and such dependencies are never
> > a good thing to rely on.
>
> There might be cases when one moves between Python and Jython, indeed.
> When one knows s/he works with Python only, it is good style to rely on
> the refcount behaviour, as it yields code which is not only more legible,
> but also more elegant and concise. [...]

   "Explicit is better than implicit."  (about the close() here)

[The code was...
>>> stuff = "stuff to write"
>>> open('stufffile', "w").write(stuff)
>>> open('stufffile', "r").read()
]

One day, you may change the code slightly,
write several lines between the two open()
commands, etc.  Then it may happen that your
program stops to work and it will be more
difficult to discover what is the problem.

In my opinion, the *short code* does not
automatically mean the *elegant*.  The shorter
it is, the more difficult may be to notice the implicit
actions inside (look at the Perl-golf tournaments
fot the example).

> [...] We understand
> that the limitation comes from the fact Jython relies on the Java system
> for collecting garbage.  One has to close explicitly in Jython for
practical
> implementation considerations, this has nothing to do with good style.

I would consider this example a bad style in any
language, independently of having or not having
the garbage collector.  The main problem is not with
the file object, but with the open file as with
the system resource -- see below.

"François Pinard"  wrote in another message...
>
> This is surely good to explicitly `close()' when one is done with a file,
> but needs to keep a reference on this file for other reasons.  The nicest
> is not keeping a reference to the file, whenever it can be avoided easily.

Well, but such "laziness" may lead to problems.
What happens when it is not possible to write
into the 'stuffile'.  In such case, it is handy to have
access to the file object (the reference to the file
object).  Because of the brevity of the code it is also
not so explicitly visible what the write() will do when
the file cannot be opened.

The opened file (when not needed) may cause
problems to other applications that try to do
something with the same file.  One should not consider
any open file object as the exclusive property
of the running application.  Because of that,
the file should be closed as soon as possible.
But nobody forces you to do it this way.
It is just a good programming practice that help
to avoid possible problems.

--
Petr Prikryl (prikrylp at skil dot cz)





More information about the Python-list mailing list