Too many return-statements = bad style?

Michael Geary Mike at Geary.com
Wed Jul 14 19:04:00 EDT 2004


> Michael Geary wrote:
> > I'd vote for this:
> >
> > f = file(...)
> > for line in f:
> >     [ process line from file ]
> > f.close()
> >
> > Actually, my favorite is the Ruby version:
> >
> > File.open(...).each do |line|
> >     [ process line from file ]
> > end

Terry Reedy wrote:
> I presume this is equivalent to Python's
>
> for line in file(...):
>   process(line)
>
> [which] is the proper way in Python also.  With iterators, for
> loops make many awkward while loops obsolete.

Yes, it's very similar, but not quite the same. The Python version still
needs the explicit close() if you want to make sure the file is closed at
the end of the loop. (As you know, in CPython the file will be closed when
all references to f are released, but Jython won't close the file until f is
garbage collected.)

The Ruby code always closes the file when the code block (the loop body)
exits, even if the code block raises an exception. So, the Ruby code:

File.open(...).each do |line|
    [ process line from file ]
end

is a closer match to this Python code:

f = file(...)
try:
    for line in f:
        [ process line from file ]
finally:
    f.close()

-Mike





More information about the Python-list mailing list