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

Andrew Barnert abarnert at yahoo.com
Fri Feb 21 08:31:42 CET 2014


On Feb 20, 2014, at 22:47, David Mertz <mertz at gnosis.cx> wrote:

> This seems *so* close to what itertools.takewhile() does that it's really hard for me to see why we need special syntax for it.

Nick Coghlan made the same observation last time around.

The counter is that if clauses in comprehensions are just as close to what filter() does and we have special syntax for them.

But I think that's a false analogy. I wrote up a blog post at http://stupidpythonideas.blogspot.com/2013/07/syntactic-takewhile.html that you might find interesting.

It's also worth looking at the other already-working alternatives from the thread, like putting a StopIteration-raising function in the expression or a higher if clause.

Also, variations of the idea have come up multiple times before that, and in 2009 one of them was written up as PEP 3142 to be officially rejected.

> On Thu, Feb 20, 2014 at 6:13 PM, Carl Smith <carl.input at gmail.com> 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. Besides, overloading `while` is much cuter...
>> 
>>     ls = [ expr for name in iterable while expr ]
>> 
>>     ls = [ expr for name in iterable if expr while expr ]
>> 
>>     ls = [ expr for name in iterable if expr else expr while expr ]
>> 
>> With regular generator expressions, it gives you a kind of base case, which may assist with showing off.
>> 
>> _______________________________________________
>> Python-ideas mailing list
>> Python-ideas at python.org
>> https://mail.python.org/mailman/listinfo/python-ideas
>> Code of Conduct: http://python.org/psf/codeofconduct/
> 
> 
> 
> -- 
> Keeping medicines from the bloodstreams of the sick; food 
> from the bellies of the hungry; books from the hands of the 
> uneducated; technology from the underdeveloped; and putting 
> advocates of freedom in prisons.  Intellectual property is
> to the 21st century what the slave trade was to the 16th.
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140220/6b6fb579/attachment.html>


More information about the Python-ideas mailing list