[Python-ideas] Add "while" clauses to generator expressions

Steven Bethard steven.bethard at gmail.com
Sat Jan 10 20:33:25 CET 2009

On Sat, Jan 10, 2009 at 7:35 AM, Gerald Britton
<gerald.britton at gmail.com> wrote:
> I would like to know if anyone has thought of adding a "while" clause
> as well, like this:
> a = (i for i in range(100) while i <=50)

I think this could end up being confusing. Current generator
expressions turn into an equivalent generator function by simply
indenting the clauses and adding a yield, for example:

    (i for i in range(100) if i % 2 == 0)

is equivalent to:

    def gen():
        for i in range(100):
            if i % 2 == 0:
                yield i

Now you're proposing syntax that would no longer work like this.
Taking your example:

    (i for i in range(100) while i <= 50)

I would expect this to mean:

    def gen():
        for i in range(100):
            while i <= 50:
                yield i

In short, -1. You're proposing to use an existing keyword in a new way
that doesn't match how generator expressions are evaluated.

I'm not *in*-sane. Indeed, I am so far *out* of sane that you appear a
tiny blip on the distant coast of sanity.
        --- Bucky Katt, Get Fuzzy

More information about the Python-ideas mailing list