Ternery operator

Michael Chermside mcherm at mcherm.com
Tue Sep 9 08:26:38 EDT 2003


Uwe Schmitt writes:
> Normaly[sic] you should simulate "C ? T : F"
> 
> either by
>              [T,F][not C]
> 
> or
> 
>              (C and [T] or [F])[0]
> 
> in the first case T and F are evaluated[sic] allways[sic],
> the latter solution does short circuit evaluation,
> which is according to the C/C++ semantics of the
> ternary operator.

NOT TRUE!

NEITHER of your options does short-circuit evaluation. That's
part of why many people (myself included) wanted to have a
conditional expression (more accurate term than "ternary operator").
If you want short-circuit evaluation (and sometimes you DO need
it), then use this:

    if C:
        x = T
    else:
        x = F

If you are writing a lambda expression, or are in some other location
where an expression would be simpler and clearer than a 4-line
statement, then too bad. There DO exist alternatives, but they are
even more obscure than Uwe's examples above, and should NOT be used
unless you are writing an obfuscated Python entry.

-- Michael Chermside






More information about the Python-list mailing list