sabbahillel sabbahillel - 1 month ago 5
Python Question

Is there a way in python to show how a line is interpreted?

When running python there is an interpretation question based on

>>> 5 > 25 == False
False
>>> (5 > 25) == False
True


Since this was a question about order of operation, I would like to actually see how the python interpreter actually handles the two statements. Is there a method to do so?

Answer

The ast module can show an abstract syntax tree for an expression or statement:

>>> import ast
>>> ast.dump(ast.parse('5 > 25 == False'))
'Module(body=[Expr(value=Compare(left=Num(n=5), ops=[Gt(), Eq()], comparators=[Num(n=25), NameConsta
nt(value=False)]))])'
>>> ast.dump(ast.parse('(5 > 25) == False'))
'Module(body=[Expr(value=Compare(left=Compare(left=Num(n=5), ops=[Gt()], comparators=[Num(n=25)]), o
ps=[Eq()], comparators=[NameConstant(value=False)]))])'

The dis module can show bytecode:

>>> import dis
>>> dis.dis('5 > 25 == False')
  1           0 LOAD_CONST               0 (5)
              3 LOAD_CONST               1 (25)
              6 DUP_TOP
              7 ROT_THREE
              8 COMPARE_OP               4 (>)
             11 JUMP_IF_FALSE_OR_POP    21
             14 LOAD_CONST               2 (False)
             17 COMPARE_OP               2 (==)
             20 RETURN_VALUE
        >>   21 ROT_TWO
             22 POP_TOP
             23 RETURN_VALUE
>>> dis.dis('(5 > 25) == False')
  1           0 LOAD_CONST               0 (5)
              3 LOAD_CONST               1 (25)
              6 COMPARE_OP               4 (>)
              9 LOAD_CONST               2 (False)
             12 COMPARE_OP               2 (==)
             15 RETURN_VALUE

dis can also operate on the the compiled bytecode stored in a function, and also as a standalone utility with python3 -m dis.