PEP 308: Erik's alternatives list - another suggestion

Detlef Lannert lannert at
Wed Feb 19 18:30:25 CET 2003

Erik, thank you for compiling this list of proposals!  I'd vote against
the introduction of any new special characters into Python syntax,
as I think there could come up better reasons for using "?" or "@"
for some other new concept, which would be more compelling than a
ternary operator ... which, as a separate concept, I don't find
_that_ useful.

I hope the following suggestion hasn't already been beaten to
death somewhere; pardon me if it has.

I'd like to suggest a syntactical construct which I'd call
a "generator comprehension".  It would resemble the list
comprehension, but instead of building a static list object,
it evaluates its components lazily when being asked for the next

For example, an iteration like

    x = 99.
    for value in [from a(x), b(x), c(x)]:
        if not value: break
        print value

evaluates a(99.) first, tests/prints its value, then evaluates
b(99.) -- which happens to be False -- and terminates.  Thus it
doesn't call c.  The [from ...] would act very much like

    def gen_com():
        yield a(x)
        yield b(x)
        yield c(x)

The "generator comprehension" could select and modify its values
on the fly, with nearly the same syntax that list comprehensions

    [v[1] for v from a(x), b(x), c(x)]

produces the same values as

    [v[1] for v in a(x), b(x), c(x)]

does today, just evaluates its components lazily.

Then we could actually use the already-proposed bool.choose()

    (x < 3).choose([from a(x), b(x)])

Or let the generator comprehension, for instance, pick its first
true value:

    [from a(x), a(x+1), a(x+2)].firsttrue()

If such a beast was indexed, it wouldn't need to evaluate all
its components up to the index:

    [from a(x), b(x), c(x)][2]

would just evaluate c(x), as a and b are not needed to determine
the result.

Pros and cons that I can (or believe to) see myself:

 + Supports a PEP-308-like "ternary operator".
 + May also be useful for very different purposes.
 + Doesn't introduce new keyword nor special character.
 + Doesn't actually introduce new concepts into the language;
   generators are already there (albeit not for long ;).
 + Symmetry with list comprehension.
 - Symmetry with list comprehension: could be confused.
 - Doesn't come to mind if a C programmer is looking for an
   equivalent of x ? y : z.

More pros and cons?  Probably.


More information about the Python-list mailing list