[Python-ideas] Change how Generator Expressions handle StopIteration

Guido van Rossum guido at python.org
Tue Nov 4 01:29:31 CET 2014


On Mon, Nov 3, 2014 at 1:38 PM, Greg Ewing <greg.ewing at canterbury.ac.nz>
wrote:

> Guido van Rossum wrote:
>
>  FWIW the implementation of my proposal is easy to describe (which the Zen
>> approves of): when a StopIteration leaves a frame, replace it with some
>> other exception (either a new, custom one or maybe just RuntimeError),
>> chaining the original StopIteration.
>>
>
> Wouldn't that break all existing iterators whose next() method
> is implemented in Python? Since the code that catches the
> StopIteration is always in a different frame then.
>
> Or are you only talking about generator frames here, not
> frames in general?
>

I have to apologize, I pretty much had this backwards.

What I should have said is that a generator should always be terminated by
a return or falling off the end, and if StopIteration is raised in the
generator (either by an explicit raise or raised by something it calls) and
not caught by an except clause in the same generator, it should be turned
into something else, so it bubbles out as something that keeps getting
bubbled up rather than silently ending a for-loop. OTOH StopIteration
raised by a non-generator function should not be mutated.

I'm sorry if this invalidates Nick's endorsement of the proposal.

I definitely see this as a serious backward incompatibility: no matter how
often it leads to buggy or obfuscated code, it's how things have always
worked.

Regarding Akira Li's examples of groupby(), unfortunately I find both
versions inscrutable -- on a casual inspection I have no idea what goes on.
I would have to think about how I would write groupby() myself (but I'm
pretty sure I wouldn't us functools.partial(). :-)

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


More information about the Python-ideas mailing list