[Python-ideas] Is this PEP-able? for X in ListY while conditionZ:

Nick Coghlan ncoghlan at gmail.com
Thu Jun 27 01:20:43 CEST 2013


On 27 Jun 2013 08:57, "David Mertz" <mertz at gnosis.cx> wrote:
>
> On Wed, Jun 26, 2013 at 3:39 PM, Alexander Belopolsky <
alexander.belopolsky at gmail.com> wrote:
>>
>> I can do this with generators now:
>>
>> >>> def stop():
>> ...    raise StopIteration
>> ...
>> >>> list(i for i in range(10) if i < 3 or stop())
>> [0, 1, 2]
>>
>> Can't the same be allowed in compehensions?
>
>
> This will only work in generator comprehensions.  The reasons are obvious
if you think about it.  But it isn't too ugly as a technique, IMO.  I still
like the 'while' clause in generators (notwithstanding the fact it doesn't
translate straightforwardly to an "unrolled block"), but this is sort of
nice (and maybe I'll start using it):
>
> >>> dict((i,i*2) for i in range(10) if i < 3 or stop())
> {0: 0, 1: 2, 2: 4}

I'm personally not opposed to allowing "else break" after the if clause as
a way of terminating iteration early in comprehensions and generator
expressions, as it's consistent with the existing translation to an
explicit loop:

{i:i*2 for i in range(10) if i<3 else break}

I'd even be OK with the use of an "else" clause to define alternative
entries to use when the condition is false:

{i:i*2 for i in range(10) if i<3 else i:i}

A reasonable constraint on the complexity may be to disallow mixing this
extended conditional form with the nested loop form.

I suspect Guido still won't be a fan either way, though :)

Cheers,
Nick.

>
> Even though this happens:
>
> >>> {i:i*2 for i in range(10) if i<3 or stop()}
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "<stdin>", line 1, in <dictcomp>
>   File "<stdin>", line 1, in stop
> StopIteration
>
> --
> Keeping medicines from the bloodstreams of the sick; food
> from the bellies of the hungry; books from the hands of the
> uneducated; technology from the underdeveloped; and putting
> advocates of freedom in prisons.  Intellectual property is
> to the 21st century what the slave trade was to the 16th.
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130627/6eb02bd3/attachment.html>


More information about the Python-ideas mailing list