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

Fred L. Drake fdrake at cnri.reston.va.us
Tue May 25 12:35:19 EDT 1999


news.eunet.no writes:
 > def iif(x, a, b):
 >   if x:
 >     return a
 >   else:
 >     return b

  Assuming you're emulating "x ? a : b"....
  This isn't quite it.  Using C's ?:, only one of a or b is evaluated
when the expression is evaluated.  iif(x, a, b) evaluates both a and
b.  Sometimes this is acceptable, but not if either a or b has side
effects or is expensive to evaluate.
  I don't think there's a good way to do this in Python right now; we
have to use an if in the context where we need the result:

     if x:
         result = a
     else:
         result = b

(Unless, of course, we happen to like some of those hideous constructs 
needed to sidestep the problem.)
  Perhaps Python 2 can fix this shortcoming; I'd often like to use
something equivalent to ?:.


  -Fred

--
Fred L. Drake, Jr.	     <fdrake at acm.org>
Corporation for National Research Initiatives




More information about the Python-list mailing list