Sub topic 8
Mutating a Global Object Versus Rebinding Its Name
This chapter assumes you can define and call functions, read a simple traceback, and use lists and dictionaries. It also assumes you know the rule from the previous chapters: an assignment inside a function makes that name local to the function, unless a global or nonlocal statement says otherwise.
That rule applies to names, not to objects. Many scope bugs come from confusing the two. This chapter separates changing an object from changing which object a name points to.
Two different operations
A name is a label attached to an object. Python can do two things with that pair:
- Rebinding attaches the name to a different object. Syntax such as
x = ...,x += ...,for x in ...,import x, anddef xall bind the namex. - Mutating changes the contents of the object the name already points to. Calls such as
items.append(1)andsettings["debug"] = Truedo this.
Scope rules only care about binding. Python decides whether a name is local by looking for binding operations on it inside the function body. A mutation is not a binding, so it doesn't make anything local.
Mutation works without `global`
Here is the simplest case:
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. The lookup falls through from local scope to global scope and finds the list. Then .append changes that list. The name items still points to the same object, which is why the id is unchanged. Nothing was bound, so no global statement is needed.
Item assignment and attribute assignment work the same way:
settings = {"debug": False}
class Config:
pass
config = Config()
def enable_debug():
settings["debug"] = True
config.name = "app"
enable_debug()
print(settings)
print(config.name)
# Output:
# {'debug': True}
# appThe statement settings["debug"] = True looks like an assignment, but it is really a call to settings.__setitem__("debug", True). The target is a subscript, not a bare name. Likewise, config.name = "app" sets an attribute on an object and doesn't bind config.
Rebinding fails without `global`
Replacing the whole object is a different matter:
items = []
def reset_items():
items = []
reset_items()
print(items)
# Output: []This runs without error, but it doesn't do what the author probably wanted. items = [] creates a new local name. The global list is untouched. If the global list had held data, it would still hold it after the call.
The error is more obvious when you read the name before binding it:
items = []
def add_item(value):
items = items + [value]
add_item(1)
# UnboundLocalError: cannot access local variable 'items' where it is not associated with a valueThe assignment makes items local for the whole function body. The right-hand side items + [value] is evaluated first and tries to read the local name, which has no value yet. The exact wording of the message varies between Python versions.
The `+=` trap
Augmented assignment is the case that surprises most people. For a list, items += [value] mutates the list in place by calling list.__iadd__. But Python still finishes the statement by binding the result back to the name. That makes it a binding operation, so items becomes local:
items = []
def add_item(value):
items += [value]
add_item(1)
# UnboundLocalError: cannot access local variable 'items' where it is not associated with a valueSo items += [value] and items.append(value) look like they do the same thing, but only the second works without a global statement. If you do declare global items, the += version works and still mutates the original list in place:
items = [1]
alias = items
def extend_items(value):
global items
items += [value]
def replace_items(value):
global items
items = items + [value]
extend_items(2)
print(items, alias, alias is items)
replace_items(3)
print(items, alias, alias is items)
# Output:
# [1, 2] [1, 2] True
# [1, 2, 3] [1, 2] FalseAfter extend_items, alias sees the change, because both names point to the same list that was mutated. After replace_items, items points to a brand-new list, and alias still points to the old one. This difference matters whenever another part of the program holds a reference to the original object.
Immutable objects force rebinding
Integers, strings, tuples, and frozensets can't be mutated. You can't "change" the integer 0 into 1. The only way to update a counter is to bind its name to a new object, which means a function that updates a module-level counter needs global:
count = 0
def increment():
global count
count += 1
increment()
increment()
print(count)
# Output: 2The same applies to strings. text += "!" builds a new string and rebinds text. A tuple behaves the same way: point += (1,) creates a new tuple.
The table below summarizes which operations need a scope declaration.
| Operation inside a function | Binds the name? | Needs `global` to affect the module-level object? |
|---|---|---|
| `items.append(1)` | No | No |
| `items[0] = 9` | No | No |
| `settings["k"] = v` | No | No |
| `config.attr = v` | No | No |
| `items += [1]` | Yes | Yes, otherwise `UnboundLocalError` |
| `items = []` | Yes | Yes, otherwise a new local is created |
| `count += 1` (int) | Yes | Yes |
| `del items` | Yes | Yes |
The last row catches people out. del items removes the name from its scope, so Python treats it as a binding operation. By contrast, del items[0] removes an element and is a mutation.
Function parameters are local names too
The same distinction explains a common surprise about arguments. A parameter is a local name bound to the object the caller passed in. Mutating that object is visible to the caller. Rebinding the parameter isn't:
def reset(values):
values = []
def clear(values):
values.clear()
nums = [1, 2]
reset(nums)
print(nums)
clear(nums)
print(nums)
# Output:
# [1, 2]
# []In reset, the local name values is pointed at a new empty list, and the caller's list is left alone. In clear, the method acts on the shared object. Notice that no global is involved at all. The rule is the same, just applied to a local name.
Why mutation hides problems
Because mutation needs no declaration, a function can change shared state without any sign in its code that it does so. A global statement at least tells the reader that the function rebinds something outside itself. A call like items.append(value) looks the same whether items is a local list or a module-level list.
This causes several problems in practice:
- Hidden coupling. Two functions that both mutate the same module-level list depend on each other's call order.
- Hard testing. State left over from one test leaks into the next, unless you reset it explicitly.
- Surprising aliases. Any other name bound to the same object sees the change, as the
aliasexample above shows. - Threading. Mutating a shared list or dict from several threads needs coordination. Rebinding a name doesn't remove that need.
Rebinding with global has its own cost. Code that did from module import count earlier holds a reference to the old object and won't see the new binding. For example, from counters import count copies the binding at import time, so later global count updates in counters aren't reflected in the importing module. Mutable containers avoid that particular problem because every holder shares one object.
Choosing an approach
When a function needs to work with shared state, there are usually better options than either global or hidden mutation:
- Pass the object in and return the result.
def add_item(items, value): return items + [value]has no scope dependency and is easy to test. - Pass the container in and mutate it deliberately. If the caller supplies the list, the mutation is visible at the call site:
add_item(items, 1). - Group state in a class or closure. A class with an
itemsattribute, or thenonlocalclosure from the previous chapter, keeps the state in one place and gives it a name. - Keep module-level constants immutable. Use tuples,
frozenset, ortypes.MappingProxyTypefor configuration that shouldn't change, so an accidental mutation raises an error instead of silently altering shared data.
from types import MappingProxyType
_defaults = {"debug": False}
DEFAULTS = MappingProxyType(_defaults)
def enable_debug():
DEFAULTS["debug"] = True
try:
enable_debug()
except TypeError as exc:
print(exc)
# Output: 'mappingproxy' object does not support item assignmentWhen you do need a module-level mutable object, such as a cache or a registry, mutating it is usually clearer than rebinding it with global. Name it so the intent is plain, such as _cache, and put the code that changes it in one or two functions.
Summary of the rules
- Scope is decided by binding operations on a name, not by changes to the object it refers to.
- Methods like
append, item assignment, and attribute assignment never make a name local. - Augmented assignment (
+=) always binds, even when the object mutates itself in place. - Immutable objects can only be "changed" by rebinding, which needs
globalornonlocalfor names outside the function. - Rebinding a parameter doesn't affect the caller. Mutating the object it points to does.
Exercise
A module defines log = [] and a function def record(msg): log += [msg]. Calling record("hi") raises UnboundLocalError. Give two different fixes, one that keeps the augmented assignment and one that needs no scope declaration.
Show answer
Fix one: add global log as the first line of record, so that += binds the module-level name and extends the list in place. Fix two: replace the body with log.append(msg) (or log.extend([msg])), which only mutates the list and never binds the name log, so it stays a global lookup.
Exercise
Given a = [1], b = a, and a function that does global a followed by a = a + [2], what do a and b contain after the call, and are they the same object?
Show answer
a is [1, 2] and b is still [1]. The expression a + [2] builds a new list and a is rebound to it, so a and b are no longer the same object. If the function had used a += [2] or a.append(2) instead, both names would show [1, 2] because the original list would be mutated.