Names, Objects, and Bindings

Understand what assignment changes, when two names share an object, and why update order matters in everyday programming.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
2 min
In this article4 chapters
  1. Bind and rebind
  2. When sharing becomes visible
  3. Read the references behind a nested structure
  4. Handle equality and sharing explicitly

Bind and rebind

Python assignment associates a name with an object. The right-hand expression is evaluated before that target is bound. If a = 5 is followed by b = a and then a = 9, the binding of b still refers to five. A familiar mathematical equality is symmetric. An assignment has a direction and a particular time in the program.

When sharing becomes visible

Start with first = [5] and second = first. Appending nine to first makes second show [5, 9] too because both bindings still reference the same list. Assigning first = [0] afterward leaves second pointing at the earlier list. Record list mutations separately from rebindings when tracing a program.[1][2]

Read the references behind a nested structure

Imagine a shopping list whose outer rows describe separate baskets. In baskets = [["tea"], ["rice"]], the outer list contains references to two inner lists. The index expression baskets[0] gives you the first inner list. After assigning today = baskets[0], the name today and the first slot of baskets hold the same reference. Appending coffee through today therefore changes what you see through the first slot.

Now set baskets[0] = ["milk"]. That assignment changes the first slot in the outer list. It leaves today referring to the earlier inner list, still containing tea and coffee. The two updates are easy to distinguish in a drawing. First you changed the contents of the inner box. Then you changed the arrow going from one slot of the outer box to an inner box.

Handle equality and sharing explicitly

Two separately built lists containing milk give a successful equality test in Python. An identity comparison on those two list objects is false. A calculation that only reads their data can use equality. A reader investigating whether an append appears in both places also needs identity and mutability. Using integers for this experiment is less informative because integers are immutable and a runtime can reuse some objects.

Try to predict the result of making a list(baskets) copy and then appending to one of the inner lists. This creates another outer list but copies the references in its slots. The append is visible through both lists. To make a genuinely independent basket snapshot, copy each inner list as well. The necessary copy depth follows from which parts of the data a later operation may change.

References

  1. Python Software Foundation, Python Language Reference: Execution Model ↩
  2. Python Software Foundation, Python Language Reference: Expressions ↩