Python quirk in evaluation order

Albert Hopkins marduk at letterboxes.org
Fri Jul 31 16:33:00 EDT 2009


On Fri, 2009-07-31 at 13:11 -0700, James Stroud wrote:
> 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?

Yes, the right hand side of the '=', which is evaluated from LtoR.

>From the Language Reference:

        Python evaluates expressions from left to right. Notice that
        while evaluating an assignment, the right-hand side is evaluated
        before the left-hand side.

So the right-hand side of the '=' is evaluated first:

    4 if True else b

And that's evaluated from left to right:

   4

Therefore:

b = 4






More information about the Python-list mailing list