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

Chris Angelico rosuav at gmail.com
Fri Nov 21 22:55:53 CET 2014


On Sat, Nov 22, 2014 at 6:33 AM, Chris Barker <chris.barker at noaa.gov> wrote:
> And I think from the perspective of the author of a given generator
> function, they should look as much the same as possible-- i.e. if a
> StopIteration is raised internally, it will behave the same way as it would
> in a iterator class.

Ah, but why? When you write a function like this:

def gen():
    yield 1
    yield 2

why should StopIteration mean any more to it than, say, KeyError does?

>> It creates a
>> separation between "iterator protocol" (which is implemented by
>> __next__) and "generator protocol" (which is written in the body of a
>> function with 'yield' in it).
>
>
> terminology messing me up here -- I understood the "iterator protocol" top
> mean the __iter__ and __next__ -- and a generator satisfies that protocol.
> Is there a "generator protocol" that means somethign different?

A generator *object* does. A generator *function* doesn't - it follows
a protocol that consists of the "yield" and "return" statements.

ChrisA


More information about the Python-ideas mailing list