"?:", "a and b or c" or "iif"

Evan Simpson evan at tokenexchange.com
Wed May 26 12:39:12 EDT 1999


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.

OTOH, I wouldn't mind seeing something like "choosevalue([test, value]+,
elsevalue)" in Python 2.0

a-job-for-bytecodehacks-if-I-ever-saw-one-ly y'rs
Evan Simpson

news.eunet.no wrote in message <7ieg4q$fhu$1 at elle.eunet.no>...
I see that the FAQ suggest "a and b or c" or similar for the equivalent of
the C ?: construct, but the solutions are not good, and rather ugly for
being Python code. I guess ?: is tricky to implement because of the way
Python uses :, but what about a builtin "iif"? This function exists in other
languages, and is easy to implement:

def iif(x, a, b):
  if x:
    return a
  else:
    return b

I use it quite often, as it does make the code a lot cleaner when the
functionality is needed many times in a program. But I'd like to see it as a
built-in, rather than having to type it in all over the place or put it in
some module I have to remember to distribute!









More information about the Python-list mailing list