[Python-ideas] "While" suggestion
Terry Reedy
tjreedy at udel.edu
Wed Aug 20 19:03:19 CEST 2008
Boris Borcic wrote:
> Andrew Toulouse wrote:
>> If I'm understanding you correctly, this would address something I've
>> wanted list comprehensions to do for a little while:
>>
>> [x for x in range(0,10) until greaterthanN(4,x)]
>
> Note that you can do something like
>
> >>> def yet(b) :
> if b : raise StopIteration
>
>
> >>> list(x for x in range(0,10) if not yet(x>4))
> [0, 1, 2, 3, 4]
I don't think it a good idea to abuse StopIteration in this way. It is
intended only for use in iterators. The obvious list comp abbreviation
does not work in CPython 3.0.
>>> [x for x in range(0,10) if not yet(x>4)]
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
[x for x in range(0,10) if not yet(x>4)]
File "<pyshell#4>", line 1, in <listcomp>
[x for x in range(0,10) if not yet(x>4)]
File "<pyshell#1>", line 2, in yet
if b : raise StopIteration
StopIteration
So it breaks the intended identity in Py3: list(genexp) == [genexp].
This was discussed on the Py3 dev list and it was agreed the difference
in behavior was a bug but would be difficult to impossible to fix
without performance degradation and unnecessary to fix because the
problem only arises if someone uses StopIteration outside its documented
usage in iterators.
More information about the Python-ideas
mailing list