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

Nick Coghlan ncoghlan at gmail.com
Wed Jun 26 06:45:54 CEST 2013


On 26 Jun 2013 12:20, "Steven D'Aprano" <steve at pearwood.info> wrote:
>
> On 26/06/13 04:12, Stephen J. Turnbull wrote:
>>
>> Shane Green writes:
>>
>>   > [x for x in l if x < 10 else break]?
>>
>> That's currently invalid syntax: break is a statement.  I think a
>> while clause (as suggested by David Mertz)  would be a more plausible
>> extension of syntax.
>>
>> I do think extending generator/comprehension syntax is much more
>> plausible than extending for loop syntax (for one thing, "just use
>> break" is not an answer here!)
>
>
>
> Comprehensions in Clojure have this feature.
>
> http://clojuredocs.org/clojure_core/clojure.core/for
>
> ;; :when continues through the collection even if some have the
> ;; condition evaluate to false, like filter
> user=> (for [x (range 3 33 2) :when (prime? x)]
>          x)
> (3 5 7 11 13 17 19 23 29 31)
>
> ;; :while stops at the first collection element that evaluates to
> ;; false, like take-while
> user=> (for [x (range 3 33 2) :while (prime? x)]
>          x)
> (3 5 7)
>
>
> (expr for x in seq while cond) is not expandable into a for loop in quite
the same way as (expr for x in seq if cond) is:
>
>
> result = []
> for x in seq:
>     if cond:
>         result.append(expr)
>
>
> vs
>
>
> result = []
> for x in seq:
>     if cond:
>         result.append(expr)
>     else:
>         break
>
>
> but I think it is a natural extension to the generator syntax that fills
a real need (or is at least frequently requested), is understandable, and
has precedent in at least one other language. But Nick Coghlan has ruled
it's not going to happen, although I don't understand what he had against
it.

Comprehensions are currently just syntactic sugar for particular kinds of
explicit loop, with a relatively straightforward mechanical translation
from the expression form to the statement form. That's an essential
property that helps keep Python's expression level and suite level flow
control constructs from diverging into two independent languages that
happen to share some keywords.

I would vastly prefer implementing PEP 403 to allow the iterable in a
comprehension to be a full generator function over any of the proposals to
add yet *more* statement like functionality to expressions.

Cheers,
Nick.

>
>
>
> --
> Steven
>
> _______________________________________________
> 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/20130626/a368a023/attachment-0001.html>


More information about the Python-ideas mailing list