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

Gary Herron gherron at islandtraining.com
Wed May 29 17:22:45 EDT 2002


On Wednesday 29 May 2002 01:05 pm, Sean 'Shaleh' Perry wrote:
> On 29-May-2002 Michael P. Soulier wrote:
> > On 24 May 2002 07:53:38 GMT, Markus Demleitner
> >
> > <msdemlei at tucana.cl.uni-heidelberg.de> wrote:
> >> The Jython docs state that
> >> open("some.name", "w").write(stuff)
> >> is bad programming practice (and indeed claim that in Jython,
> >> the above construct leaves some.name empty).
> >
> >     I can't speak for Jython, but in CPython 2.1, it works fine.
> >
> >>>> stuff = "stuff to write"
> >>>> open('stufffile', "w").write(stuff)
> >>>> open('stufffile', "r").read()
> >
> > 'stuff to write'
>
> yes, but can you disagree with the statement that it is bad programming
> practice.  I sure can't.

Here's why its a bad practice:

The question is: When does the file get closed?

The expectation is that the file object will be garbage collected
immediately after the statement is executed (since that's when its ref
count goes to zero), and that this will force the file to be closed.
And in fact the traditional CPython implementation of Python behaves
in exactly this way.

However, Python does not guarantee to garbage collect immediately as
the refcount goes to zero, and in fact Jython does NOT do so,instead
relying on Java's garbage collection.

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.

Gary Herron






More information about the Python-list mailing list