[Python-ideas] PEP 479: Change StopIteration handling inside generators

Chris Angelico rosuav at gmail.com
Fri Nov 21 11:26:24 CET 2014


On Fri, Nov 21, 2014 at 9:19 PM, Wolfgang Maier
<wolfgang.maier at biologie.uni-freiburg.de> wrote:
> My reason for not using a for loop here is that I'm trying to read from a
> file where several lines form a record, so I'm reading the title line of a
> record (and if there is no record in the file any more I want the parser
> generator to terminate/return. If a title line is read successfully then I'm
> reading the record's body lines inside a try/except, i.e. where it says "#
> read and process the rest of the record here" in my shortened code I am
> actually calling next several times again to retrieve the body lines (and
> while reading these lines an unexpected StopIteration in the IOWrapper is
> considered a file format error).
> I realize that I could also use a for loop and still call next(file_object)
> inside it, but I find this a potentially confusing pattern that I'm trying
> to avoid by using the while loop and all explicit next().

I agree. The last example in the PEP is a cut-down form of your
parser, and I raise the exact same concern:

https://www.python.org/dev/peps/pep-0479/#examples

The use of the for loop strongly implies that the loop body will be
executed once for each thing in the iterable, which isn't true if you
next() it in the body. Legal? Sure. Confusing? Definitely.

ChrisA


More information about the Python-ideas mailing list