AW: Ternery operator

Uwe Schmitt schmitt at procoders.net
Tue Sep 9 14:43:59 CEST 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").

The second one does short circuit evaluation, try the following:


    def T(): 
          print "T called"
          return "T"
    def F(): 
          print "F called"
          return "F"

    res1 = (1 and [T()] or [F()])[0]
    res2 = (0 and [T()] or [F()])[0]

Greetings, Uwe.








More information about the Python-list mailing list