Sub topic 7
Rebinding a global with the global statement
This chapter assumes you can define and call functions, read a simple traceback, and know that Python looks up names in the order local, enclosing, global, built-in (the LEGB rule). It also assumes you have seen that assigning to a name inside a function makes that name local.
The problem to solve
A function can read a global name without any special syntax. Rebinding is different. Any assignment to a name inside a function makes that name local to the whole function body. The result is an UnboundLocalError when the function tries to update a module-level counter.
count = 0
def increment():
count += 1
increment()
# UnboundLocalError: cannot access local variable 'count' where it is not associated with a valueThe statement count += 1 is shorthand for count = count + 1. Python sees the assignment at compile time and marks count as local. At run time the right-hand side reads a local count that has no value yet. The exact error wording differs between Python versions.
What the global statement does
The global statement tells Python that a name in this function refers to the module-level name. Assignments then rebind the global instead of creating a local.
count = 0
def increment():
global count
count += 1
increment()
increment()
print(count)
# Output: 2Rules to remember:
- Write
global namebefore the first use ofnamein the function. Using the name first and declaring it later is aSyntaxError. - The declaration applies to the whole function body, not only to the lines after it.
- You can list several names:
global a, b. - If the global does not exist yet, assigning to it after the declaration creates it at module level.
Where the declaration is needed
Only rebinding needs global. Reading does not.
| Action inside the function | Needs `global`? |
|---|---|
| Read a global name | No |
| Assign to it (`=`, `+=`, `for` target, `import`, `def`) | Yes |
| Call a method that mutates the object it refers to | No |
| Delete the name with `del` | Yes |
Many forms of binding count as assignment, not only =. A for loop target, an import statement, and a nested def all bind a name, so each makes the name local unless declared global.
The flow of a name lookup
Common errors
- Declaring too late. Placing
global countaftercounthas been used in the function raisesSyntaxError: name 'count' is used prior to global declaration. - Declaring global when you only mutate. Adding
global itemsto a function that only callsitems.append(...)does no harm, but it is unnecessary and suggests the wrong mental model. The next chapter covers mutation in detail. - Forgetting the declaration in one function. If one function declares
global countand another assigns tocountwithout it, the second function silently creates its own local variable. No error appears, and the global stays unchanged.
count = 0
def reset():
count = 0 # creates a local; the global is untouched
def increment():
global count
count += 1
increment()
reset()
print(count)
# Output: 1Use it sparingly
Functions that rebind globals have hidden inputs and outputs. They are harder to test, and any code in the module can change the shared state. Prefer passing values in as arguments and returning results.
def increment(count):
return count + 1
count = 0
count = increment(count)
count = increment(count)
print(count)
# Output: 2Exercise
In the code below, what does print(total) show, and why? What one-line change makes add update the module-level total?
total = 10
def add(n):
total = total + n
add(5)
print(total)
Show answer
The call add(5) raises UnboundLocalError before print runs. The assignment total = total + n makes total local to add, so the right-hand side reads a local that has no value yet. Adding global total as the first line of the function body makes it rebind the module-level name, and print(total) then shows 15.
Exercise
A function declares global score and then assigns score = 5, but no module-level score existed beforehand. What happens?
Show answer
No error occurs. The assignment creates score in the module's global namespace. Code that reads score before any call to this function would raise NameError.