Search code examples
pythonmathoperator-precedenceevaluationexpression-evaluation

Expression evaluation order in Python


I'd like this question answered just for curiosity's sake. In the following mathematical expression (and ones like it):

(( (3 * 7)  + 5 * ((3 - 7) + (3 * 4))) + 9)

Does Python evaluate (3 - 7) or (3 * 4) first? The thing about this is, these innermost parentheses could really be evaluated in either order and achieve the same result. But which order is used?

At this point I'm considering putting a breakpoint in the actual Python interpreter to see if I can come up with any sort of answer (as to how the parse tree is generated). Been asking on IRCs and such to no avail. Thanks for your time.


Solution

  • You can inspect the byte code to see that the left side is evaluated first:

    dis.dis("""(a - b) + (c * d)""")
      1           0 LOAD_NAME                0 (a)
                  2 LOAD_NAME                1 (b)
                  4 BINARY_SUBTRACT
                  6 LOAD_NAME                2 (c)
                  8 LOAD_NAME                3 (d)
                 10 BINARY_MULTIPLY
                 12 BINARY_ADD
                 14 RETURN_VALUE
    

    The evaluation order of expressions is part of the language specification.

    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.


    Note that if you use a literal expression, such as (3 - 7) + (3 * 4), it is not evaluated but directly compiled.

    dis.dis("""(3 - 7) + (3 * 4)""")
      1           0 LOAD_CONST               0 (8)
                  2 RETURN_VALUE