[Python-ideas] PEP 479: Change StopIteration handling inside generators
Chris Angelico
rosuav at gmail.com
Sat Nov 22 11:57:26 CET 2014
On Sat, Nov 22, 2014 at 9:48 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Sat, Nov 22, 2014 at 10:40:37AM +1100, Chris Angelico wrote:
>
>> Let's suppose you use a Python-like macro language to generate Python
>> code. In the macro language, you can write stuff like this:
>
> Is there really any point in hypothesing imaginary macro languages when
> we have a concrete and existing language (Python itself) to look at?
>
> [snip made-up example]
>
>> This is a reasonably plausible macro language, right? It's basically
>> still a class definition, but it lets you leave out a whole bunch of
>> boilerplate. Now, the question is: As you write the simplified
>> version, should you ever need to concern yourself with StopIteration?
>
> Sure, why not? It is part of the concrete protocol: iterators raise
> StopIteration to halt. That's not a secret, and it is not an
> implementation detail, it is a concrete, public part of the API.
>
>
>> I posit no, you should not; it's not a part of the macro language at
>> all.
>
> This is why talking about imaginary macro languages is pointless. You
> say it is not part of the macro language. I say it is. Since the
> language doesn't actually exist, who is to say which is right?
A generator function is exactly the same thing: it's a way to create
an iterator, but it's not a class with a __next__ function. I could
write an iterator-creation function in many ways, none of which
involve StopIteration:
def gen():
if condition: raise StopIteration # Wrong
return iter([1,2,3])
>> > and of you are writing a generator, presumably you know how it's going to
>> > get use -- i.e. by somethign that expects a StopIteration -- it's not like
>> > you're ignorant of the whole idea.
>>
>> Not necessarily. Can we get someone here who knows asyncio and
>> coroutines, and can comment on the use of such generators?
>
> What about them? I don't understand your question.
If you have a lengthy nested chain of coroutines, and one of them
unexpectedly raises StopIteration, is it right for something to
quietly terminate, or should the exception bubble up and be printed to
console?
ChrisA
More information about the Python-ideas
mailing list