"?:", "a and b or c" or "iif" (eval?)

Joshua Rosen rozzin at geekspace.com
Fri Jun 4 14:04:19 CEST 1999


Evan Simpson wrote:

> It would need to be more than built-in (in the sense of being a function
> defined in builtins) to get the semantics that I, at least, would expect
> from this kind of construct; it would need to actually be part of the
> language, so that it could do short-circuit evaluation of its parameters
> (which no function can do).

>
> In other words, your "iif" always evaluates "a" and "b", when it is often
> desirable to only evaluate "b" if "x" is false.  It's true that the
> full-blown "((test1 and [value1]) or (test2 and [value2]) or
> [elsevalue])[0]" is clunky, but it's actually fairly efficient, and not too
> bad once you've seen it twice.

    One could also probably use eval:
        eval(cond0 and "expr0" or "expr1")
    ..., though that's probably not the best way, in terms of execution-speed of
expr0 or expr1, but it does give the effect of lazy evaluation, truly doing the
short-circuit thing. Still, the syntax isn't ugly.

. o O ( Of course, I don't think that the "(cond0 and [expr0] or [expr1])[0]"
syntax is ugly, or even that "(cond0 and (expr0,) or (expr1,))[0]" is too bad,
so who am I to judge?)







More information about the Python-list mailing list