Unpacking Values and Simultaneous Assignment

Unpacking binds multiple targets from one iterable. Computing the right side first lets a pair of bindings be swapped without a temporary name.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
2 min
In this article4 chapters
  1. Trace the swap
  2. Check the structure you expect
  3. Evaluate a swap from the old bindings
  4. Check shape and shared objects separately

Trace the swap

With left = 2 and right = 7, Python left, right = right, left evaluates the objects on the right and then binds left to seven and right to two. Two ordinary assignments that reuse the updated left value would lose the original two.

Check the structure you expect

A configuration record may supply a pair of strings for a name and a port. Unpacking exposes malformed lengths immediately for normal fixed-length assignment. The port still requires explicit parsing. Tests should exercise missing fields and invalid field contents separately.[1][2]

Evaluate a swap from the old bindings

With left bound to two and right to nine, evaluating the right-hand values in left, right = right, left obtains nine and two before those names change. Binding the targets makes left nine and right two. Two statements that first replace left and then read it for right would instead leave both nine. A trace can put the pending pair in a column for the right side, then update each target from that observed pair.

Check shape and shared objects separately

An ordinary pattern with two targets expects two values. Reading a configuration row with three fields can fail even if the first two are valid. Check input length at the right abstraction level and report which source row failed. Typed input records moves numeric conversions after the needed fields have been identified.

Data binding through unpacking still follows the language's normal object rules. If a two-position value contains a list in each position, unpacking does not duplicate those lists. Mutating one can be visible through the original container. Use a fixture with distinct inner lists and test what a new caller is allowed to edit under the contract.

References

  1. Python Software Foundation, Python Standard Library: Built-in Types ↩
  2. Python Software Foundation, Python Language Reference: Expressions ↩