[Python-ideas] Is this PEP-able? for X in ListY while conditionZ:
Ron Adam
ron3200 at gmail.com
Thu Jun 27 04:44:40 CEST 2013
On 06/26/2013 06:20 PM, Nick Coghlan wrote:
> 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:
The 'else' in these cases is tricky... And may make the whole expression
look too much like a if-else expression. [See last example]
> {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}
This already works.
>>> {i:(i*2 if i<3 else i) for i in range(10)}
{0: 0, 1: 2, 2: 4, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9}
And this:
>>> [x if x<5 else 0 for x in range(10)]
[0, 1, 2, 3, 4, 0, 0, 0, 0, 0]
These take care of all one to one mapping of values.
The 'if' after the iterator handles the selection of values. Given that,
it makes sense to allow flow control statements after the last if, but not
expressions effecting the values. (Not ... else i:i)
Here are some examples of how I thinking about this...
This includes values less than limit.
[x for x in range(n) if x<limit]
is the same as... (*)
[x for x in range(n) if x<limit pass else continue]
(*we don't need this one, because the above already works this way.)
The reverse would be...
[x for x in range(n) if x<=limit continue]
And to stop early...
[x for x in range(n) if x>=limit break]
If we included else break, it would need to be spelled...
[x for x in range(n) if x<limit pass else break]
But this.... when an else immediately follows the condition...
[x for x in range(n) if x>limit else break]
Resembles an if-else expression too much... Parentheses for clarity.
result = [(x for x in range(n)) if (x<limit) else (break)]
I don't think we want that. (?)
Cheers,
Ron
> 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.
>
More information about the Python-ideas
mailing list