Sub topic 9
Pitfalls: shared references, mutable defaults, and mutable items inside tuples
This chapter assumes you know how lists, tuples, dicts, and sets behave, and that you understand mutability and hashability from the earlier chapters. It covers the mistakes that most often cause real bugs. Each one comes from the same cause: a Python variable is a name that points to an object, and several names can point to the same object.
Names are references, not copies
Assignment never copies an object. It binds a name to an object that already exists.
a = [1, 2, 3]
b = a # b is another name for the same list
b.append(4)
print(a) # [1, 2, 3, 4]
print(a is b) # True
c = a.copy() # a new list with the same items
c.append(5)
print(a) # [1, 2, 3, 4]
print(a is c) # FalseUse is to ask whether two names point to the same object. Use == to ask whether two objects have equal contents.
Immutable objects such as int, str, and tuple hide this problem because you cannot change them in place. Sharing a reference to one is harmless. The trouble starts with mutable objects: lists, dicts, sets, and instances of most classes.
Passing arguments is also sharing
Python passes a reference to the object into a function. If the function mutates a list you gave it, the caller sees the change.
def add_total(scores):
scores.append(sum(scores)) # mutates the caller's list
data = [10, 20]
add_total(data)
print(data) # [10, 20, 30]If a function should not change its input, either document that it mutates or build a new object and return it:
def with_total(scores):
return [*scores, sum(scores)]
data = [10, 20]
print(with_total(data)) # [10, 20, 30]
print(data) # [10, 20]A common convention in the standard library is that methods that mutate in place return None. list.sort() is one example. Functions that return a new object are named differently, such as sorted(). Writing items = items.sort() therefore sets items to None.
Repeating a mutable item with `*`
Multiplying a list repeats references to the same item. For numbers and strings this is fine. For lists it is a bug.
grid = [[0] * 3] * 3
grid[0][0] = 1
print(grid) # [[1, 0, 0], [1, 0, 0], [1, 0, 0]]The outer list holds three references to one inner list. Changing a cell through any row changes all rows. Build each row separately with a comprehension:
grid = [[0] * 3 for _ in range(3)]
grid[0][0] = 1
print(grid) # [[1, 0, 0], [0, 0, 0], [0, 0, 0]]The inner [0] * 3 is safe because the items are integers, which are immutable.
The same issue appears in dict.fromkeys when you pass a mutable value:
shared = dict.fromkeys(["a", "b"], [])
shared["a"].append(1)
print(shared) # {'a': [1], 'b': [1]}
separate = {key: [] for key in ["a", "b"]}
separate["a"].append(1)
print(separate) # {'a': [1], 'b': []}dict.fromkeys(keys, value) evaluates value once. A dict comprehension evaluates [] once per key.
Shallow copies and deep copies
list.copy(), dict.copy(), set.copy(), list(x), and the slice x[:] all make shallow copies. A shallow copy creates a new outer container, but the items inside are the same objects.
import copy
nested = [[1, 2], [3]]
shallow = nested.copy()
shallow[0].append(99)
print(nested) # [[1, 2, 99], [3]]
deep = copy.deepcopy(nested)
deep[0].append(100)
print(nested) # [[1, 2, 99], [3]]
print(deep) # [[1, 2, 99, 100], [3]]The table summarizes the choices.
| Operation | New outer container | New inner objects |
|---|---|---|
| `b = a` | No | No |
| `a.copy()`, `a[:]`, `list(a)` | Yes | No |
| `copy.deepcopy(a)` | Yes | Yes |
Use a shallow copy when the items are immutable, or when you will only replace items and never mutate them. Use copy.deepcopy when you need a fully independent structure. It is slower, and it handles objects that refer to themselves, but it can fail or behave unexpectedly on objects such as open files or locks.
Mutable default arguments
A function's default values are evaluated once, when the def statement runs. They are not re-evaluated on each call. If the default is mutable, every call that omits the argument shares the same object.
def add_item(item, bucket=[]):
bucket.append(item)
return bucket
print(add_item(1)) # [1]
print(add_item(2)) # [1, 2]
print(add_item.__defaults__) # ([1, 2],)The __defaults__ attribute shows that the default list lives on the function object and keeps growing. The standard fix uses None as a sentinel, a marker meaning "no value was given":
def add_item(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucket
print(add_item(1)) # [1]
print(add_item(2)) # [2]Test with is None, not if not bucket. An empty list the caller passed in is falsy, and if not bucket would silently replace it with a new list. The caller would then lose the mutation they expected.
def add_item_wrong(item, bucket=None):
if not bucket: # replaces a caller's empty list too
bucket = []
bucket.append(item)
return bucket
mine = []
add_item_wrong(1, mine)
print(mine) # [] the caller's list was ignoredSometimes a shared default is deliberate, for example a simple cache. If you do this, make it obvious with a module-level name or a comment. Do not hide it in a signature.
Mutable items inside tuples
A tuple is immutable in the sense that you cannot rebind its slots. It does not make the objects in those slots immutable. This is shallow immutability.
t = (1, [2, 3])
t[1].append(4)
print(t) # (1, [2, 3, 4])The tuple still holds the same list in slot 1. The list changed, so the tuple's visible contents changed.
The augmented assignment surprise
This case raises an error and still changes the data:
t = (1, [2, 3])
try:
t[1] += [4]
except TypeError as e:
print(e) # 'tuple' object does not support item assignment
print(t) # (1, [2, 3, 4])The statement t[1] += [4] runs in two steps. First, list.__iadd__ extends the list in place and returns it. Second, Python tries to store the result back into t[1], and the tuple refuses. The first step already happened, so you get both an exception and a modified list.
For lists, t[1].extend([4]) or t[1].append(4) expresses the intent directly and raises no error. Whether you should mutate at all is a design question. If the tuple is meant to be a fixed record, avoid putting mutable objects in it.
Consequences for hashing
A tuple is hashable only if everything inside it is hashable. A tuple that holds a list can never be a dict key or set member:
t = (1, [2, 3])
try:
hash(t)
except TypeError as e:
print(e) # unhashable type: 'list'
try:
{t: "value"}
except TypeError as e:
print(e) # unhashable type: 'list'Convert the inner list to a tuple (or the inner set to a frozenset) when you need a composite key:
key = (1, tuple([2, 3]))
lookup = {key: "value"}
print(lookup[(1, (2, 3))]) # valueHashability is checked when you insert or look up, not when you create the tuple. A tuple holding a list builds without any error.
Mutating a collection while iterating over it
Changing the size of a list, dict, or set during iteration is a related reference problem. The loop holds a position in the object you are changing.
For a list, items are skipped without any error:
nums = [2, 4, 6, 1]
for n in nums:
if n % 2 == 0:
nums.remove(n)
print(nums) # [4, 1] (4 was skipped)Removing the first item shifts the rest left, but the loop's index still advances, so it steps over one item. Build a new list instead:
nums = [2, 4, 6, 1]
nums = [n for n in nums if n % 2 != 0]
print(nums) # [1]Dicts and sets detect this and raise an error:
d = {"a": 1, "b": 2}
try:
for k in d:
if d[k] == 1:
del d[k]
except RuntimeError as e:
print(e) # dictionary changed size during iterationIterate over a snapshot, for k in list(d):, or build a new dict with a comprehension. Changing the value for an existing key is allowed, because the size does not change. Adding or removing keys is not.
Defining equality and hashing for your own classes
The same hashing rules apply to your own classes. If you define __eq__ without __hash__, Python sets __hash__ to None and the class becomes unhashable:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return isinstance(other, Point) and (self.x, self.y) == (other.x, other.y)
try:
{Point(1, 2)}
except TypeError as e:
print(e) # unhashable type: 'Point'If you do add __hash__ based on mutable attributes, then mutating those attributes after the object is in a set or used as a dict key breaks lookups. The object sits in the table under its old hash and can no longer be found. Hash only on fields that never change, or make the class immutable with @dataclass(frozen=True) or a namedtuple.
A checklist for finding these bugs
When data changes and you did not expect it, check the following in order.
- Did you assign (
b = a) where you meant to copy? - Did you use
*to repeat a list that contains mutable items? - Does a function signature contain
=[],={}, or=set()? - Does a shallow copy hold nested mutable items that you then mutated?
- Are you modifying a container while looping over it?
- Does a tuple hold a list, dict, or set that something else mutates?
The id() function and the is operator help confirm sharing. If id(a) == id(b), the two names point to one object.
Exercise
What does this code print, and why? How would you fix it so that a stays empty?
def collect(x, acc=[]):
acc.append(x)
return acc
a = collect(1)
b = collect(2)
print(a, b, a is b)
Show answer
It prints [1, 2] [1, 2] True. The default list is created once when def runs, so both calls append to and return the same object, and a and b are two names for it. The fix is to use acc=None and write if acc is None: acc = [] inside the function. Each call then gets a new list, and the output becomes [1] [2] False.
Exercise
Given t = ("id", [1, 2]), will t[1] += [3] raise an error? What is t afterward? Can you use t as a dict key?
Show answer
Yes, it raises TypeError: 'tuple' object does not support item assignment. Before the error, list.__iadd__ has already extended the inner list in place, so t is ("id", [1, 2, 3]). You cannot use t as a dict key, because hashing a tuple hashes its items and a list is unhashable, so hash(t) raises TypeError: unhashable type: 'list'. Using ("id", (1, 2)) would be hashable.
Exercise
You write board = [["."] * 3] * 3 and then set board[1][1] = "X". How many cells show X, and what single change fixes it?
Show answer
Three cells show X, one in each row, because the outer list holds three references to the same inner list. Replace the outer repetition with a comprehension: board = [["."] * 3 for _ in range(3)]. Each row is then a separate list, and only board[1][1] changes.