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

Steven D'Aprano steve at pearwood.info
Tue Jan 20 23:55:59 CET 2009

On Wed, 21 Jan 2009 03:56:06 am 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.

If that's the case, then that is a point in favour of the PEP.

Personally, I find the proposed syntax change very readable and 
intuitive. Some have argued that it makes Python harder to learn 
because it adds one more thing to learn, but that's a trivial 
objection. It's an extension to the existing syntax, but an obvious 
one. The difficulty in becoming proficient in a language is not 
learning the syntax, but in becoming experienced with the libraries, 
and on that regard the PEP is a win because it simplifies the itertools 
module by removing takewhile (which unfortunately I find neither 
readable or intuitive).

Another argument against the PEP was that it breaks the correspondence 
between the generator expression and the equivalent for-loop. I had 
never even noticed such correspondence before, because to my eyes the 
most important term is the yielded expression, not the scaffolding 
around it. In a generator expression, we have:

yielded-expr for-clause if-clause

while the corresponding nested statements are:

for-clause if-clause yielded-expr

The three clauses are neither in the same order, nor are they in reverse 
order. I don't know how important that correspondence is to language 
implementers, but as a Python programmer, I'd gladly give up that 
correspondence (which I don't find that great) in order to simplify 
exiting a generator expression early.

So I like the proposed change. I find it elegant and very Pythonic. +1 
for me.

Steven D'Aprano

More information about the Python-Dev mailing list