[Python-ideas] Change how Generator Expressions handle StopIteration

Andrew Barnert abarnert at yahoo.com
Sun Nov 2 23:37:57 CET 2014


On Nov 2, 2014, at 13:00, Terry Reedy <tjreedy at udel.edu> wrote:

> On 11/2/2014 2:50 PM, Andrew Barnert wrote:
>> This is related to the fact that, although the docs imply otherwise,
>> [COMP] isn't exactly equivalent to list(COMP),
> 
> That purported equivalence is a common meme, which I may have helped spread. If it is implied in the doc, it should be changed.  Before I answered on this thread yesterday, I looked for such an implication in the Language Reference (though not the Tutorial), and only found this carefully written description in the expressions chapter.

We looked through this last year and decided nothing needed to be changed in the docs, so I doubt it's worth repeating that effort. 

IIRC, the tutorial may have been confusing in the past but wasn't as of 3.3, and the only place that might confuse anyone was the what's new in 3.0, which is generally only changed to add notes about things which were un-/re-changed (like u"" strings). But again, even if I'm remembering wrong, I don't think it matters.

All that being said, I don't really love the reference docs here. Neither 6.2.8 not anything else explicitly says what the semantics are. It's a pretty obvious guess that the syntax is interpreted the same as for comprehensions (as in 6.2.4), and that the values yielded are those that would be used to produce elements. But the docs don't actually say that.

> "In this case, the elements of the new container are those that would be produced by considering each of the for or if clauses a block, nesting from left to right, and evaluating the expression to produce an element each time the innermost block is reached. Note that the comprehension is executed in a separate scope,"
> 
> IE, a comprehension is equivalent to the result of for and if statements in a separate Python function that first initializes a collection object (list, set, or dict) and augments the collection in the innermost scope with the element produced (which is a key,value pair for dicts).
> 
> Such an equivalent function would not catch any exception raised by the innermost element expression.  On the other hand, collection initializers, such as list or tuple, specifically catch StopIteration when fed an iterable. Hence the two cannot be equivalent when the element expression raises StopIteration.
> 
> -- 
> Terry Jan Reedy
> 
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/


More information about the Python-ideas mailing list