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

David Mertz mertz at gnosis.cx
Mon Jul 1 22:29:09 CEST 2013


On Mon, Jul 1, 2013 at 10:25 AM, Joshua Landau
<joshua.landau.ws at gmail.com>wrote:

> > primes100 = {p for p in primes(); break if p >= 100}
> > primes100 = {p for p in primes() while p < 100}
>
> If you're telling me that "{p for p in primes() while p < 100}" reads
> better than "{p for p in primes(); break if p >= 100}" I have to
> disagree strongly. The "break if" form looks beautiful.
>

My own taste is in strong contrast to Joshua's.  I think the
semi-colon/break-if looks absolutely horrendous and ugly.  The 'while'
clause looks obvious, beautiful, and intuitive.

However, I see the point made by a number of people that the 'while' clause
has no straightforward translation into an unrolled loop, and is probably
ruled out on that basis.

That said, I think the version using Guido's suggestion (and already
supported for generator comprehensions) looks fairly nice.  I.e. given a
support function:

  def stopif(x):
      if x: raise StopIteration
      return True

We can express it as:

  primes100 = set(p for p in primes() if stopif(p >= 100))

Except I'm not sure I like the spelling of 'stopif()', since the repeating
the 'if' in the function name reads oddly.  I guess I might like this
spelling better:

  primes100 = set(p for p in primes() if still(p < 100))  # Obvious
implementation of still()

The only change we need is the one Guido has declared as "do it" which is
to make other comprehensions act the same as the instantiation with the
generator.  I.e. this should work:

  primes100 = {p for p in primes() if still(p < 100)}

It doesn't *really* matter whether someone likes my spelling 'still()' or
Guido's 'stopif()' better, since either one is trivially implementable by
end users if they wish to do so.

-- 
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.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130701/a9d8273d/attachment.html>


More information about the Python-ideas mailing list