Interpreting Left to right?

Terry Reedy tjreedy at udel.edu
Fri Jun 24 02:20:11 EDT 2011


On 6/24/2011 12:32 AM, Chetan Harjani wrote:
> x=y="some string"
> And we know that python interprets from left to right.

Read the doc. "5.14. Evaluation order
Python evaluates expressions from left to right. Notice that while 
evaluating an assignment, the right-hand side is evaluated before the 
left-hand side."

> another example:
> (1,2) + 3,
> here, python raises a  TypeError "can only concatenate tuple(not int) to
> tuple" but we know (3,) is a tuple as seen by following:

But "(3,) is not what you wrote;-). The comma operator has the lowest 
precedence, although this is not as clear in the doc as it should be. 
Your expression is parsed as ((1,2)+3),. Parentheses have the highest 
precedence. The combination of both facts is why tuples often need to be 
parenthesized, as it should be here and why you added the first pair 
instead of writing 1,2 + 3,.

Disassembly of bytecode shows how an expression was parsed.
 >>> from dis import dis
 >>> dis('(1,2)+3,')
   1           0 LOAD_CONST               3 ((1, 2))
               3 LOAD_CONST               2 (3)
               6 BINARY_ADD
               7 BUILD_TUPLE              1
              10 RETURN_VALUE

-- 
Terry Jan Reedy




More information about the Python-list mailing list