an ugly file-reading pattern

Jp Calderone exarkun at intarweb.us
Tue Apr 15 13:19:05 EDT 2003


On Tue, Apr 15, 2003 at 03:28:31PM +0000, Robin Munn wrote:
> Jp Calderone <exarkun at intarweb.us> wrote:
> > On Mon, Apr 14, 2003 at 06:53:32PM +0200, Avner Ben wrote:
> >> 
> >> "Robin Munn" <rmunn at pobox.com> wrote in message
> >>
> >> > You're right, I didn't close the file explicitly. But explicit is better
> >> > than implicit, so IMHO it's better to give a name to the file object so
> >> > that you can close it explicitly:
> >> >
> >> >     input_file = file("somefile")
> >> >     for line in input_file:
> >> >         process(line)
> >> >     input_file.close()
> >> 
> >> 
> >>     The C# language has a nice construct: using (variable = whatever) { /*
> >> code */ }. The variable in the using header is guaranteed to be
> >> garbage-collected at the end of the block (or so I think). Could be useful
> >> here.
> >> 
> > 
> >   In CPython, the reference count to the file object in:
> > 
> >     for line in file(...):
> >         ...
> > 
> >   will drop to 0 immediately after the loop, and the file will be closed at
> > that point.
> 
> But the Python language spec doesn't guarantee that objects will be
> garbage-collected immediately when their refcount drops to 0; 

  Python language spec? >:)  I thought CPython was the language spec, for
all practical purposes.

> and, in fact, Jython does *not* garbage-collect zero-refcount objects
> immediately. Relying on garbage-collection is not safe. For most
> operations, it's safe enough (if a file stays open a bit longer than you
> expected, it's probably not a big deal) but there are times when it is
> important to know exactly when the file is closed; I prefer to simply make
> a habit of it.

  I agree.  What I would *really* like to see is a PEP from the "with ...:"
construct debate that occurred several weeks ago on python-dev.

  Jp

-- 
No, `Eureka' is Greek for `This bath is too hot.'
                -- Dr. Who
-- 
 up 26 days, 13:02, 2 users, load average: 0.00, 0.02, 0.04





More information about the Python-list mailing list