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

Scott Dial scott+python-dev at scottdial.com
Mon Jan 19 19:41:57 CET 2009


Vitor Bosshard wrote:
> Are you even sure the list comprehension doesn't already shortcut evaluation?

It does not. The body of the comprehension is evaluated all the way to
completion, despite the fact that a.next() does not return until there
is a successful test of the if expression.

>>> def print_range(n):
...     for i in range(n):
...         print(i)
...         yield i
...
>>> a = (i for i in print_range(10) if i**2<10)
>>> a.next()
0
0
>>> a.next()
1
1
>>> a.next()
2
2
>>> a.next()
3
3
>>> a.next()
4
5
6
7
8
9
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

-- 
Scott Dial
scott at scottdial.com
scodial at cs.indiana.edu


More information about the Python-Dev mailing list