Understanding python parallel assignment
parallel assignment
parallel assignment is the process of assigning more than one variable in parallel.
A classic use case of parallel assignment swapping in python. If parallel assignment was not there, we would have to use a temporary variable for swapping. With parallel assignment the code is more elegant and readable.
What happens behind the scenes?
A tuple is a collection of values separated by commas. tuples have two operations
- Packing
- Unpacking
Tuple packing
packing allows to create tuples.
Tuple unpacking
Tuples unpacking allows to assign values from tuple to separate variables.
Using python dis module, I am analysing the opcode to understand how it works.
The RHS is evaluated first. The BUILD_TUPLE creates a tuple and pushes the result into the stack. Next the LHS is evaluated The ‘UNPACK_SEQUENCE’ pops the tuples and pushes each of elements of stack from right to left into stack. STORE_FAST would store the top of stack into the variable.
for assignment with two or three variables python would use the stack directly. This is a peephole optimisation in python. Analysing using dis.
ROT_TWO opcode would just swap the topmost stack elements.