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

Steven D'Aprano steve at pearwood.info
Tue Nov 25 16:20:24 CET 2014


On Mon, Nov 24, 2014 at 10:22:54AM +1100, Chris Angelico wrote:

> 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

I wouldn't interpret it like that.

Calling next() on an empty iterator raises StopIteration. That's not a 
bug indicating a failure, it's the protocol working as expected. Your 
response to that may be to catch the StopIteration and ignore it, or to 
allow it to bubble up for something else to deal with it. Either way, 
next() raising StopIteration is not a bug, it is normal behaviour.

(Failure to deal with any such StopIteration may be a bug.)

However, if next() raises RuntimeError, that's not part of the protocol 
for iterators, so it is almost certainly a bug to be fixed. (Probably 
coming from an explicit "raise StopIteration" inside a generator 
function.) Your fix for the bug may be to refuse to fix it and just 
catch the exception and ignore it, but that's kind of nasty and hackish 
and shouldn't be considered good code.

Do you agree this is a reasonable way to look at it?


-- 
Steven


More information about the Python-Dev mailing list