[Python-ideas] Allowing breaks in generator expressions by overloading the while keyword

Steven D'Aprano steve at pearwood.info
Fri Feb 21 11:24:03 CET 2014


On Fri, Feb 21, 2014 at 02:13:13AM +0000, Carl Smith wrote:
> Sometimes you need to build a list in a loop, but break from the loop if
> some condition is met, keeping the list up to that point. This is so common
> it doesn't really need an example.
> 
> Trying to shoehorn the break keyword in to the generator expression syntax
> doesn't look pretty, unless you add `and break if expr` to the end, but
> that has its own issues. 

The main issue being that it gives a SyntaxError :-)


> Besides, overloading `while` is much cuter...
> 
>     ls = [ expr for name in iterable while expr ]

I would *love* this syntax. I've read the various arguments against it, 
and they don't convince me. It is functionality which is often needed 
and requested, e.g.

http://stackoverflow.com/questions/5505891/using-while-in-list-comprehension-or-generator-expressions


Clojure has list comprehensions that behave this way:

http://clojuredocs.org/clojure_core/clojure.core/for


but alas both Nick Coglan and (if I recall correctly) Guido have ruled 
that Python won't get this, so until the Revolution comes, it isn't 
going to happen.



-- 
Steven


More information about the Python-ideas mailing list