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

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue Jul 2 14:28:53 CEST 2013


On 2 July 2013 00:34, MRAB <python at mrabarnett.plus.com> wrote:
>
> So:
>
>     for item in generator while is_true(item):
>         ...
>
> is equivalent to:
>
>     for item in generator:
>         if not is_true(item):
>             break
>         ...
>
> By similar reasoning(?):
>
>     for item in generator if is_true(item):
>         ...
>
> is equivalent to:
>
>     for item in generator:
>         if not is_true(item):
>             continue
>         ...
>
> If we have one, shouldn't we also have the other?
>
> If only comprehensions have the 'if' form (IIRC, it has already been
> rejected for multi-line 'for' loops), then shouldn't only
> comprehensions have the 'while' form?

<if> is allowed in comprehensions and loops. I'm only suggesting that
for/while wouldn't unroll the same way that for/if does. To me it
seems natural that <while> "binds" more tightly to <for> than <if>
does. The <if> clause in a comprehension is about per item logic so it
belongs in the body of the loop. The proposed <while> clause would
affect the flow of the loop globally so it does not.

Also I wouldn't propose that for/while is equivalent to for/if/break
in the case that there is an else clause. This is one area where
takewhile is better than for/if/break since you can do

    for item in takewhile(lambda: keep_going, iterable):
        if acceptable(item):
            break
    else:
        raise Error('No acceptable items')

instead of

    for x in iterable:
        if not keep_going:
            raise Error('No acceptable items')
        elif acceptable(item):
            break
    else:
        raise Error('No acceptable items')

I would want to be able to write

    for item in iterable while keep_going:
        if acceptable(item):
            break
    else:
        raise Error('No acceptable items')

and know that either an error was raised or item is bound to an
acceptable object.


Oscar


More information about the Python-ideas mailing list