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

David Mertz mertz at gnosis.cx
Thu Jun 27 00:56:34 CEST 2013


On Wed, Jun 26, 2013 at 3:39 PM, Alexander Belopolsky <
alexander.belopolsky at gmail.com> wrote:

> I can do this with generators now:
>
> >>> def stop():
> ...    raise StopIteration
> ...
> >>> list(i for i in range(10) if i < 3 or stop())
> [0, 1, 2]
>
> Can't the same be allowed in compehensions?
>

This will only work in generator comprehensions.  The reasons are obvious
if you think about it.  But it isn't too ugly as a technique, IMO.  I still
like the 'while' clause in generators (notwithstanding the fact it doesn't
translate straightforwardly to an "unrolled block"), but this is sort of
nice (and maybe I'll start using it):

>>> dict((i,i*2) for i in range(10) if i < 3 or stop())
{0: 0, 1: 2, 2: 4}

Even though this happens:

>>> {i:i*2 for i in range(10) if i<3 or stop()}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <dictcomp>
  File "<stdin>", line 1, in stop
StopIteration

-- 
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/20130626/840f6342/attachment.html>


More information about the Python-ideas mailing list