[Python-Dev] PEP 3142: Add a "while" clause to generator expressions

Cameron Simpson cs at zip.com.au
Tue Jan 20 03:54:49 CET 2009

On 19Jan2009 19:42, Calvin Spealman <ironfroggy at gmail.com> wrote:
| OK, I still don't like the general idea, but I have a suggestion for
| what I think is a more favorable syntax, anyway. Basically, adding the
| allowance of an 'else break' when there is an if clause in a generator
| expression or list comprehension. I still dont think it should be
| done, but it is a more consistent syntax. It has the obvious problem
| of looking like it might allow an alternative expression, like the
| if-expression.
| prime = (p for p in sieve() if p < 1000 else break)

If I'm reading your suggestion correctly it changes feel of the "if"
part quite fandamentally. A bare "if" acts as a filter, yielding only
the items matching the condition. With an "else break" it yields only
the items matching the condition up to the first which fails.

For a range like "p < 1000" this isn't so different, but if the condition
doesn't apply to just the leading items then this form becomes almost
useless. Consider "p % 3 == 0". Normally that would yield every third
item. With "else break" it would yield just one item. Any non-continuous
filter has the same issue.

In my opinion this makes the construct far less applicable than it would
appear at first glance.

So -1 from me.

I saw someone else mention takewhile(), and that's my preferred way
of doing the original suggestion ("[ ... while some-constraint ]"),
and thus I'm -1 on the original suggestion too (also for the if/while
confusion mentioned in the thread).

Cameron Simpson <cs at zip.com.au> DoD#743

Drive Agressively  Rash Magnificently   - Nankai Leathers

More information about the Python-Dev mailing list