Python quirk in evaluation order

Robert Kern robert.kern at gmail.com
Fri Jul 31 22:31:21 CEST 2009


On 2009-07-31 15:11, 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?

The right side of the assignment or the if-else expression? The "expr1 if 
condition else expr2" expression evaluates condition, then either expr1 or expr2 
depending on the result. The other expression is unevaluated.

 >>> a
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
 >>> b
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined
 >>> 5 if True else b
5
 >>> a if False else 5
5

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list