Tracing Python expression evaluation step by step

后端 未结 3 1884
你的背包
你的背包 2020-12-10 04:20

I\'m trying to write Python expression evaluation visualizer, that will show how Python expressions are evaluated step by step (for education purposes). Philip Guo\'s Python

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-10 04:48

    Why not use the dis module?

    Since CPython compiles Python to bytecode and runs that, looking at the bytecode gives you the best idea of what actually happens.

    In [1]: import dis
    
    In [2]: dis.dis('sorted([4, 2, 3, 1] + [5, 6])[1] == 2')
      1           0 LOAD_NAME                0 (sorted)
                  3 LOAD_CONST               0 (4)
                  6 LOAD_CONST               1 (2)
                  9 LOAD_CONST               2 (3)
                 12 LOAD_CONST               3 (1)
                 15 BUILD_LIST               4
                 18 LOAD_CONST               4 (5)
                 21 LOAD_CONST               5 (6)
                 24 BUILD_LIST               2
                 27 BINARY_ADD
                 28 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
                 31 LOAD_CONST               3 (1)
                 34 BINARY_SUBSCR
                 35 LOAD_CONST               1 (2)
                 38 COMPARE_OP               2 (==)
                 41 RETURN_VALUE
    

    Edit: An alternative method could be to show the steps one-by-one in IPython:

    In [1]: [4, 2, 3, 1]
    Out[1]: [4, 2, 3, 1]
    
    In [2]: [4, 2, 3, 1] + [5, 6]
    Out[2]: [4, 2, 3, 1, 5, 6]
    
    In [3]: sorted([4, 2, 3, 1, 5, 6])
    Out[3]: [1, 2, 3, 4, 5, 6]
    
    In [4]: [1, 2, 3, 4, 5, 6][1]
    Out[4]: 2
    
    In [5]: 2 == 2
    Out[5]: True
    

提交回复
热议问题