[Python-ideas] "Iteration stopping" syntax [Was: Is this PEP-able? for X in ListY while conditionZ:]
Guido van Rossum
guido at python.org
Sun Jun 30 22:52:01 CEST 2013
I apologize, this thread was too long for me to follow. Is the issue
the following?
>>> def stopif(x):
... if x: raise StopIteration
... return True
...
>>> [i for i in range(10) if stopif(i==3)]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
File "<stdin>", line 2, in stopif
StopIteration
>>> list(i for i in range(10) if stopif(i==3))
[0, 1, 2]
I.e. the difference between list(<genexp>) and [<genexp>] is that if
<genexp> raises StopIteration, list(...) returns the elements up to
that point but [...] passes the exception out?
That seems a bug to me inherited from the Python 2 implementation of
list comprehensions and I'm fine with fixing it in 3.4. The intention
of the changes to comprehensions in Python 3 was that these two forms
would be completely equivalent. The difficulty has always been that
CPython comprehensions were traditionally faster than generator
expressions and we're reluctant to give that up. But it's still a bug.
--
--Guido van Rossum (python.org/~guido)
More information about the Python-ideas
mailing list