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

Guido van Rossum guido at python.org
Fri Nov 21 00:51:07 CET 2014


On Thu, Nov 20, 2014 at 2:39 PM, Wolfgang Maier <
wolfgang.maier at biologie.uni-freiburg.de> wrote:

> [...]
> Hmm, I'm not convinced by these toy examples, but I did inspect some of my
> own code for incompatibility with the proposed change. I found that there
> really is only one recurring pattern I use that I'd have to change and that
> is how I've implemented several file parsers. I tend to write them like
> this:
>
> def parser (file_object):
>     while True:
>         title_line = next(file_object) # will terminate after the last
> record
>
>         try:
>             # read and process the rest of the record here
>         except StopIteration:
>             # this record is incomplete
>             raise OSError('Invalid file format')
>         yield processed_record
>
> So I'm catching StopIteration raised by the underlying IOWrapper only if
> it occurs in illegal places (with regard to the file format the parser
> expects), but not when it indicates the end of a correct file.
> I always thought of letting the Error bubble up as a way to keep the
> parser transparent.
> Now in this case, I think, I would have to change this to:
>
> def parser (io_object):
>     while True:
>         try:
>             title_line = next(io_object)
>         except StopIteration:
>             return
> ...
>
> which I could certainly do without too much effort, but could this be one
> of the more widespread sources of incompatibility that Steve imagines ?


There's probably something important missing from your examples. The above
while-loop is equivalent to

    for title_line in io_object:
        ...

If you're okay with getting RuntimeError instead of OSError for an
undesirable StopIteration, you can just drop the except clause altogether.

-- 
--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20141120/8c3568d2/attachment.html>


More information about the Python-ideas mailing list