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

Chris Angelico rosuav at gmail.com
Mon Nov 24 00:22:54 CET 2014


On Mon, Nov 24, 2014 at 10:18 AM, Ron Adam <ron3200 at gmail.com> wrote:
>> The stop hack won't work in either (currently it does work in
>> genexps), but you'd get a different exception type if you attempt it.
>> This is correct. It's broadly similar to this distinction:
>>
>>>>> >>>{1:2,3:4}[50]
>>
>> Traceback (most recent call last):
>>    File "<stdin>", line 1, in <module>
>> KeyError: 50
>>>>>
>>>>> >>>[1,2,3,4][50]
>>
>> Traceback (most recent call last):
>>    File "<stdin>", line 1, in <module>
>> IndexError: list index out of range
>
>
> Comprehensions insert/append items, so you wouldn't get those unless you are
> reading from another object and would bubble out of generators too. Which is
> good because it's most likely an error that needs fixing.

My point is that doing the same errant operation on a list or a dict
will give different exceptions. In the same way, calling next() on an
empty iterator will raise StopIteration normally, but might raise
RuntimeError instead. It's still an exception, it still indicates a
place where code needs to be changed (unlike, say, a ValueError when
doing type conversions, which often means *data* needs to be changed),
so it doesn't hugely matter _which_ exception is raised. Also, I'm
hoping that someone can improve on my patch by having the full
traceback from the original StopException become visible - then, the
RuntimeError's __context__ will give all the info you would want.

ChrisA


More information about the Python-Dev mailing list