Tuples and Mutable Contents
A tuple's element positions stay fixed. The objects in those positions can still change when they support mutation.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 2 min
In this article4 chapters
Predict an inner update
Start with record = ("draft", [3]). Appending four to the list yields a tuple displaying ("draft", [3, 4]) because the second position still refers to that list. Assigning a replacement into record[1] raises a type error. See mutable values for the role of that shared reference.
Check a key design
Using the record as a dictionary key fails because the list inside is unhashable. Converting the inner list to a tuple of integers gives a hashable snapshot. A hashable key needs stable equality for its entire use as a key.[1][2]
Observe a mutation behind a fixed slot
Let a tuple hold an identifier and a list of tags. With ("north", ["draft"]), adding checked to the contained list changes the displayed tuple contents to show draft and checked. Both positions in the tuple continue referring to the original objects. Assigning a different object to the second tuple slot raises an error under ordinary Python tuple semantics. See mutable and immutable values for why the container's own permitted updates do not constrain every referenced object.
Choose an immutable form for a historical key
If a lookup should use the tags at the time of a snapshot, convert the current list of strings to a tuple and store the identifier and that tuple together. Later appends to the original list cannot change the earlier sequence of strings. If outer members contain mutable records, select explicit immutable fields or copy more deeply.
Try taking two snapshots separated by one append, and verify both snapshots' values. Then pass the snapshot to a dictionary and test lookup of an independently built equal value. Hashable keys describe why the properties of all relevant components matter.