[Python-Dev] PEP 3142: Add a "while" clause to generator expressions

rdmurray at bitdance.com rdmurray at bitdance.com
Tue Jan 20 19:08:00 CET 2009


On Tue, 20 Jan 2009 at 16:56, Antoine Pitrou wrote:
> Alexey G. Shpagin <python-3000 <at> udmvt.ru> writes:
>>
>> Example will look like
>>  g = (n for n in range(100) if n*n < 50 or else_break())
>
> Please don't suggest any hack involving raising StopIteration as part of a
> conditional statement in a generator expression. It might work today, but it
> might as well break tomorrow as it's only a side-effect of the implementation,
> not an official property of the language.

Doing the above is, by definition, no different from raising StopIteration
in a for loop inside a generator function.  The language reference does
document the raising of a StopIteration as signaling the exhaustion of
the generator.  In addition, the 3.0 docs (but, oddly, not the 2.6 docs)
say in the 'for' loop documentation: "When the items are exhausted (which
is immediately when the list is empty or an iterator raises a
StopIteration exception)").

The difference in behavior between raising StopIteration in a list
comprehension versus a generator expression are consistent with the
above, by the way.  If you raise StopIteration in a function whose
definition is the same as the list comprehension but you are building
the list as you go and only returning it when it is complete, then
the StopIteration would propagate upward with no values returned (ie:
in a for loop it would look like an empty list).

I don't know about other people, but I have certainly assumed that raising
StopIteration was a legitimate way to terminate an iterator, and have
written code accordingly.  If this is not true, it should probably be
explicitly documented in the language reference somewhere.

--RDM


More information about the Python-Dev mailing list