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

François Pinard pinard at iro.umontreal.ca
Thu May 30 11:38:29 EDT 2002


[The message sent to Peter bounced, let me send it to the list instead.]

[Petr Prikryl]

>    "Explicit is better than implicit."

This is another ex-cathedra principle.  Do you explicitly `del NAME' for
all your local variables, at the end of a function?  The system does it
implicitly for you, and we are all very happy with this.

There is an equilibrium between explicit and implicit, and a sense of good
taste going in that equilibrium.  But good taste in Python is not the same
as for Perl or for C, we need to un-dust ourselves a bit when we switch
between languages.

> In my opinion, the *short code* does not automatically mean the *elegant*.

Fully agreed, there is no guarantee there.  On the other hand, it sometimes
happens that elegant code is shorter.  No reason to feel shy! :-)

> The main problem is not with the file object, but with the open file as
> with the system resource -- see below.

Which open file?  It gets closed as soon as expected!

> > The nicest is not keeping a reference to the file, whenever it can be
> > avoided easily.

> Well, but such "laziness" may lead to problems.

This is no `laziness' at all.  This is an active seek for legibility.
I want my code to go straight to the essentials, and that it shows those
essentials as clearly as possible.  I probably write and rewrite my code
much more patiently than many people do, with that goal always in mind.

> What happens when it is not possible to write into the 'stuffile'.
> [...]  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.

Python will traceback, magically, wonderfully, with adequate information.

> 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 this is exactly what happens.  There is no problem, only fears.  Once you
get use to the paradigm, you discover that it is safe and dependable.

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






More information about the Python-list mailing list