The following Python code:
a = 1
b = 2
a, b = b, a
compiles to the following Python bytecode:
1 0 LOAD_CONST 0 (1)
2 STORE_NAME 0 (a)
2 4 LOAD_CONST 1 (2)
6 STORE_NAME 1 (b)
3 8 LOAD_NAME 1 (b)
10 LOAD_NAME 0 (a)
12 ROT_TWO
14 STORE_NAME 0 (a)
16 STORE_NAME 1 (b)
18 LOAD_CONST 2 (None)
20 RETURN_VALUE
According to Python's docs, the instruction ROT_TWO
swaps the order of the first two elements of the stack.
I'm having a hard time understanding why this is necessary.
My understanding is that, in order to swap a
and b
, you could just push a
, then push b
, then store the stacktop in a
, then store the stacktop in b
, achieving the variable swap. Something like this:
1 0 LOAD_CONST 0 (1)
2 STORE_NAME 0 (a)
2 4 LOAD_CONST 1 (2)
6 STORE_NAME 1 (b)
3 8 LOAD_NAME 1 (b)
10 LOAD_NAME 0 (a)
14 STORE_NAME 1 (b)
16 STORE_NAME 0 (a)
18 LOAD_CONST 2 (None)
20 RETURN_VALUE
Why is this extra operation needed? Is there any advantage to doing it over the solution I suggested?