[Python-ideas] Change how Generator Expressions handle StopIteration

Terry Reedy tjreedy at udel.edu
Sun Nov 2 22:00:46 CET 2014


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.

"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



More information about the Python-ideas mailing list