Ternary Operator
Terry Reedy
reedy37 at home.com
Fri May 18 13:05:16 EDT 2001
"Stefan Kirchberg" <sk at gluit.de> wrote in message
news:3B054397.71A1A29F at gluit.de...
> Hi,
>
> I just read section 4.16 of The Whole Python FAQ
> (http://www.python.org/doc/FAQ.html#4.16). It states that as an
> equivalent to C/C++'s
> a? b : c
> expression, the Python expression
> a and b or c
> has a flaw if b evaluates to 0 (false)
However, if one knows that b cannot be false, this works wonderfully.
> and the expression
> (a and [b] or [c])[0]
> being a possible solution. Unfortunately, the latter one seems
> kind of obfuscated to me...
>
> Now, how about
> [b,c][not a]
Your alternative requires that both b and c be computed, regardless of the
value of a, which is a flaw when either b or c will raise an exception if a
has the wrong value. Guarding the computation of b by precondition a is a
common use of ternarys. Consider
y and x/y or None # or (y and (x/y,) or (None,))[0] # versus
(x/y,None)[not y]
TJ Reedy
More information about the Python-list
mailing list