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

Andrew Barnert abarnert at yahoo.com
Fri Jun 28 18:44:11 CEST 2013


On Jun 28, 2013, at 1:20, "Wolfgang Maier" <wolfgang.maier at biologie.uni-freiburg.de> wrote:

> Let me suggest one more solution although it requires a new keyword:
> introduce
> 
> *breakif* condition
> 
> and define its translation as if condition: break .

This is basically the same idea as the until statement (with the opposite truth sense, but all of these are easy to invert)--except that it doesn't introduce a block. This means you can't nest anything underneath it, which means it doesn't work in comprehensions without changing what comprehensions mean. 

So, it combines the disadvantages of the until solution, because it introduces a new statement that no one will ever use just to provide a meaning for a comp clause that people might, and the various break solutions (other than "make break an expression), because it requires complicating the definition of what comprehensions do. 

That being said, it clearly reads differently from an until clause or an else break clause intuitively.

I think that gives me a glimmer of a better way to organize the choices into a few (not completely independent) ideas organized in a tree, with different options (e.g., choice of keyword or syntax) for most of them.

I'll try to write it up later, after letting it stew for a while, but the basics are something like:

 * No syntax change, just make existing things easier to use (e.g., builtin takewhile)
 * Breaking expressions (e.g., break as expression)
  * making comprehensions StopIteration-able (e.g., redefine as list(genexp)
 * Breaking clauses
  * that fit nesting rule as-is
   * by also adding a new statement (until)
   * by explicitly defining what they map to instead of just "the equivalent statement" (magic while)
  * that require redefining comprehensions (else break)
   * by also adding a new statement or modifying an existing one (ifbreak)

We'd still need to list the specific versions of each category, because they definitely read differently, especially in simple comprehensions (a simple expression, one for, and the new clause)--which, as people have pointed out, are the most important ones (you can teach novices how to use and read simple comps without explaining the nesting rule, and that should still be true).
> You can now write
> (x for x in iterable breakif x < 0)
> and I don't see a way how that could possibly be misread by anyone.
> Also it would translate unambiguously to the explicit:
> 
> for x in iterable:
>    breakif x<0 # itself translating to if x<0: break
>    yield x
> 
> It would work with genexps, comprehensions and explicit loops alike (with
> very
> little benefit for the later, though maybe it increases readability even
> there
> by making it clear from the start of the line what the purpose of the
> condition
> test is).


More information about the Python-ideas mailing list