"?:", "a and b or c" or "iif"
Michael Vanier
mvanier at bbb.caltech.edu
Tue May 25 20:29:49 EDT 1999
"Fred L. Drake" <fdrake at cnri.reston.va.us> writes:
> 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
This sounds like another job for bytecodehacks :-)
I personally detest the ?: operator in C, mainly because people who use it
tend to write fun code like this:
a = (b ? (c ? d : (e ? f : g)) : (h ? i : j));
If something like this is coded, I *strongly* recommend that it not be an
operator but something like an "iif"-type function. Of course, to do that,
you need to be able to define functions with lazy evaluation. THAT would be a
neat thing to have in python 2.0! E.g.:
# Warning: pseudo-python ahead!
def iif(condition, consequent, alternative):
lazy consequent, alternative
if (condition):
return consequent
else:
return alternative
With-lazy-evaluation-can-true-macros-be-far-away-ly y'rs,
Mike
-------------------------------------------------------------------------
Mike Vanier mvanier at bbb.caltech.edu
Department of Computation and Neural Systems, Caltech 216-76
Will optimize nonlinear functions with complex parameter spaces for food.
More information about the Python-list
mailing list