Python quirk in evaluation order

Dave Angel davea at ieee.org
Fri Jul 31 17:07:01 EDT 2009


James Stroud wrote:
> <div class="moz-text-flowed" style="font-family: -moz-fixed">Python 2.5:
>
> mbi136-176 211% python
> *** Pasting of code with ">>>" or "..." has been enabled.
> ########################################################################
>  ##                             ipython                              ##
> ########################################################################
> py> b = 4 if True else b
> py> b
> 4
>
>
> Isn't the right side supposed to be evaluated first?
>

I don't have a clue what value you expected b to have.  The if/else 
ternary expression is roughly equivalent to:
              if True:
                    b = 4
              else
                    b = b
The first part to be evaluated is the if expression, which is hard-coded 
to True.  Then the part to the left will be used for the expression 
result, and the part on the right ignored.  This is because of 
short-circuit rules.

Try this one for size:
b = 22 if True else  I.am.Not.Being.Evaluated(4.4)

The else clause does need to be a syntactically valid expression, but 
it's not evaluated unless the if-expression is false.

DaveA





More information about the Python-list mailing list