[Python-ideas] "Iteration stopping" syntax [Was: Is this PEP-able? for X in ListY while conditionZ:]

Joshua Landau joshua.landau.ws at gmail.com
Mon Jul 1 00:00:08 CEST 2013


On 30 June 2013 21:52, Guido van Rossum <guido at python.org> wrote:
> 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.

But which way is the bug?

Personally, the list comprehension has it right. I'd prefer if
(raise_stopiteration() for _ in [0]) actually had the StopIteration
fall through.


More information about the Python-ideas mailing list