Conditional operator in Python?
aleax at aleax.it
Tue Sep 4 10:07:53 CEST 2001
"Weet Vanniks" <Weet.Vanniks at el_simpatico.be> wrote in message
news:3B947E32.C5604328 at el_simpatico.be...
> What about :
> def cond_choose(cond,first_choice,second_choice):
> if cond:
> return first_choice
> return second_choice
> whatever= cond_choose(x,a,b)
> This seems much cleaner to me than all those contorsions with the syntax.
It is, but it has entirely different semantics: BOTH a
and b are FULLY evaluated BEFORE one of them is chosen.
This is totally inappropriate for many uses of 'choice',
such as guarding against incorrect operations, controlling
recursion, and so on.
result = cond_choose(x, 23/x, 149)
this tries to compute 23/x even when x is zero. This is NOT
the correct semantics for conditional-choice. Any of
the alternative approaches, such as:
result = (x and 23/x) or 149
WILL behave correctly: since and/or "short-circuit", the
right-hand-side operand is *NOT* evaluated -- the division
by zero will not happen with this coding.
More information about the Python-list