Sub topic 8
Mutating a global object versus rebinding its name
This chapter assumes you know how LEGB lookup works and why assigning to a name inside a function makes that name local. It builds on both.
Two different operations
A name is a label attached to an object. Two things can happen to a global variable:
- Rebinding points the name at a different object. This is what assignment does.
- Mutating changes the contents of the object the name already points to. Methods like
appenddo this.
The global statement only matters for rebinding. Mutation never changes which object the name refers to, so Python needs no permission to do it.
items = []
def add_item(value):
items.append(value)
before = id(items)
add_item(1)
add_item(2)
print(items)
print(id(items) == before)
# Output:
# [1, 2]
# TrueInside add_item, the name items is only read. Python finds it in the global scope, and .append changes the list in place. The id check confirms it is still the same object.
Rebinding creates a local name
Writing items = [...] inside a function is an assignment. Python treats items as local for the whole function, and the global list is untouched.
items = ["a"]
def reset():
items = []
items.append("b")
reset()
print(items)
# Output: ['a']The function filled a new local list and discarded it. If you want to rebind the global, declare it:
items = ["a"]
def reset():
global items
items = ["b"]
reset()
print(items)
# Output: ['b']Operations that look like mutation but rebind
Augmented assignment (+=) is the common trap. For a list, items += [3] mutates the list in place. Python still finishes by assigning the result back to the name, so the name counts as an assignment target and becomes local.
items = [1, 2]
def extend():
items += [3]
extend()
# UnboundLocalError: cannot access local variable 'items' where it is not associated with a valueThe fix is to use a method call, which only reads the name:
items = [1, 2]
def extend():
items.extend([3])
extend()
print(items)
# Output: [1, 2, 3]Item and slice assignment such as items[0] = 9 is different. It calls a method on the object, and the name items is not an assignment target. So it works without global.
Immutable objects must be rebound
Integers, strings, and tuples cannot be changed in place. Any "change" creates a new object, so changing a global of those types always requires rebinding, and therefore global.
| Operation inside a function | Rebinds the name? | Needs `global`? |
|---|---|---|
| `items.append(x)` | No | No |
| `items[0] = x` | No | No |
| `items = []` | Yes | Yes, to affect the global |
| `items += [x]` | Yes | Yes, or use `extend` |
| `count += 1` (int) | Yes | Yes |
Common errors
- Writing
items = []to "clear" a global list inside a function. Useitems.clear()to empty the same object, or declareglobal items. - Using
+=on a global list withoutglobal, which raisesUnboundLocalError. - Adding
globalwhen the function only calls methods. It does no harm, but it suggests the name is rebound and misleads readers.
Exercise
A module defines total = 0 and log = []. A function does total += 5 and log.append(total). Which line raises UnboundLocalError, and what is the smallest change that fixes it?
Show answer
total += 5 raises it, because augmented assignment rebinds total, which makes it local, and no value exists yet to read. Adding global total at the top of the function fixes it. The log.append(total) line needs no change, because it only mutates the list.