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

Ronald Oussoren ronaldoussoren at mac.com
Tue Jul 2 14:08:29 CEST 2013


On 29 Jun, 2013, at 12:09, Nick Coghlan <ncoghlan at gmail.com> wrote:

...
> 
> 
> Rather than adding a new keyword, we could simply expand the syntax
> for the existing break statement to be this:
> 
>    break [if <EXPR>]

That saves types two characters as compared with current status-quo ;-)


> 
> This would simplify the above two standard idioms to the following:
> 
>    while True:
>        # Iteration setup
>        break if termination_condition
>        # Remainder of iteration
> 
>    for x in data:
>        break if desired_value(x)
>    else:
>        raise ValueError("Value not found in {:100!r}".format(data))
> 
> A "bare" break would then be equivalent to "break if True". The "else"
> clause on the loop could then be *explicitly* documented as associated
> with the "break if <X>" form - the else only executes if the break
> clause is never true. (That also becomes the justification for only
> allowing this for break, and not for continue or return: those have no
> corresponding "else" clause)
> 
> Once the break statement has been redefined this way, it *then*
> becomes reasonable to allow the following in comprehensions:
> 
>    data = [x for x in iterable break if x is None]

> 
> As with other proposals, I would suggest limiting this truncating form
> to disallow combination with the filtering and nested loop forms (at
> least initially). The dual use of "if" would make the filtering
> combination quite hard to read, and the nested loop form would be
> quite ambiguous as to which loop was being broken. If we start with
> the syntax restricted, we can relax those restrictions later if we
> find them too limiting, while if we start off being permissive,
> backwards compatibility would prevent us from adding restrictions
> later.

Jikes. I don't like restricting this to loops without filtering and without nesting at all, that makes the language more complex.  Has anyone tried to inventory how often this new syntax would be appropriate (with and without the restriction on filtering and nested loops)?

> 
> I'd be very keen to see this written up as a PEP - it's the first
> proposal that I feel actually *simplifies* the language in any way
> (mostly by doing something about those perplexing-to-many else clauses
> on for and while loops).

That's very optimistic, I don't think this helps with the for:else: confusion at all. The else part of a for loop already has a straightforward explanation, and that doesn't seem to help at all. An if-component on a 'break' statement has a pretty loose connection to the corresponding 'else', especially when the 'if' part is optional.

Ronald


More information about the Python-ideas mailing list