Search code examples
python-3.xbytecode

Analysing a Python bytecode


In the following Python bytecode, I would like to understand why the value of i is not incremented just before JUMP_ABSOLUTE ?

>>> import dis
>>> dis.dis("""for i in range(4):
...     print(i)
... """)
  1           0 SETUP_LOOP              24 (to 26)
              2 LOAD_NAME                0 (range)
              4 LOAD_CONST               0 (4)
              6 CALL_FUNCTION            1
              8 GET_ITER
        >>   10 FOR_ITER                12 (to 24)
             12 STORE_NAME               1 (i)

  2          14 LOAD_NAME                2 (print)
             16 LOAD_NAME                1 (i)
             18 CALL_FUNCTION            1
             20 POP_TOP
             22 JUMP_ABSOLUTE           10
        >>   24 POP_BLOCK
        >>   26 LOAD_CONST               1 (None)
             28 RETURN_VALUE

Solution

  • The evolution of i is simply done at the line 10 by calling the magic method __next__ of range.