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

Sturla Molden sturla at molden.no
Tue Jan 20 17:08:48 CET 2009

On 1/20/2009 4:45 PM, Gerald Britton wrote:
> OK, so your suggestion:
>  g = (n for n in range(100) if n*n < 50 or raiseStopIteration())
> really means "return in in the range 0-99 if n-squared is less than 50
> or the function raiseStopIteration() returns True".
> How would this get the generator to stop once n*n >=50? It looks
> instead like the first time around, StopIteration will be raised and
> (presumably) the generator will terminate.

I still find it odd to invent new syntax for simple things like

def quit(): raise StopIteration

gen = itertools.imap( lambda x: x if x <= 50 else quit(),
                       (i for i in range(100)) )

for i in gen: print i

Sturla Molden

More information about the Python-Dev mailing list