RE: Ternery operator

Discussion in 'Python' started by Michael Chermside, Sep 9, 2003.

1. Michael ChermsideGuest

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

Michael Chermside, Sep 9, 2003

2. Andrew KoenigGuest

Michael> 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.

Michael> NOT TRUE!

Michael> NEITHER of your options does short-circuit evaluation. That's
Michael> part of why many people (myself included) wanted to have a
Michael> conditional expression (more accurate term than "ternary
Michael> operator").

NOT TRUE! The second option does short-circuit evaluation:

(C and [T] or [F])[0]

--
Andrew Koenig,

Andrew Koenig, Sep 9, 2003

3. Erik Max FrancisGuest

Michael Chermside wrote:

> Uwe Schmitt writes:
>
> > Normaly[sic] you should simulate "C ? T : F"
> >
> > either by
> > [T,F][not C]
> >
> > or
> >
> > (C and [T] or [F])[0]
> > ...

>
> NOT TRUE!
>
> NEITHER of your options does short-circuit evaluation.

The latter does, due to its use of and/or. An equivalent form including
lambdas is

(C and lambda: T or lambda: F)()

--
Erik Max Francis && && http://www.alcyone.com/max/
__ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/ \ Silence is the most perfect expression of scorn.
\__/ George Bernard Shaw

Erik Max Francis, Sep 9, 2003