Sub topic 7
Rebinding a Global with the global Statement
This chapter assumes you can define and call functions, read a simple traceback, and use lists. It also assumes you know that Python looks up names through local, enclosing, global, and built-in scopes, and that assigning to a name inside a function makes that name local. Here you will learn how the global statement overrides that default, what it changes, and what it does not.
The problem the statement solves
Reading a global name from inside a function works, because lookup falls through from the local scope to the global scope:
count = 0
def read_count():
return count
print(read_count())
# Output: 0Rebinding is different. If a function assigns to a name, Python decides at compile time that the name is local for the whole function body. The earlier assignment rule then produces an error:
count = 0
def increment():
count += 1
increment()
# UnboundLocalError: cannot access local variable 'count' where it is not associated with a valueThe statement count += 1 means count = count + 1. Python sees the assignment, makes count local, and then fails when it reads the local count before it has a value. The exact wording of the message varies between Python versions.
What the global statement does
The global statement tells the compiler that the listed names, within the current function, refer to the module-level names. Every binding operation on those names then changes the module's namespace instead of creating a local variable.
count = 0
def increment():
global count
count += 1
increment()
increment()
print(count)
# Output: 2The syntax is global name1, name2, .... You can list several names in one statement.
low = 0
high = 0
def reset_bounds(new_low, new_high):
global low, high
low = new_low
high = new_high
reset_bounds(5, 10)
print(low, high)
# Output: 5 10The declaration is a compile-time directive, not a runtime action. It does not copy anything and it does not run when the line is reached. It only changes which namespace the function's name operations target.
Which operations count as rebinding
Plain assignment is not the only way to bind a name. With a global declaration, all of these affect the module-level name:
- Assignment (
x = 1) and augmented assignment (x += 1). - A
forloop target (for x in ...). import xandfrom m import x.def x():andclass x:.with ... as x.del x.
For example, a function can set up a lazily imported module as a global:
def load_json():
global json
import json
load_json()
print(json.dumps({"ok": True}))
# Output: {"ok": true}This pattern works, but it hides an import inside a function and makes the module's state depend on call order. Treat it as an illustration of the rule, not a recommendation.
The name does not have to exist yet
A global declaration does not require the module-level name to exist already. If the function assigns to it, Python creates it in the module namespace at that moment.
def init_config():
global config
config = {"debug": True}
init_config()
print(config)
# Output: {'debug': True}Until init_config() runs, reading config anywhere raises NameError. That makes the module's names depend on which functions have been called. It is a common source of bugs, which is why linters often warn about defining globals inside functions.
Mutation does not need global
The global statement matters only for rebinding. Calling a method that changes an object does not rebind the name, so no declaration is needed:
items = []
def add_item(value):
items.append(value)
add_item(1)
add_item(2)
print(items)
# Output: [1, 2]If you add global items here, nothing changes in behavior. It is harmless but misleading, because it suggests the function rebinds items. A later chapter compares mutation and rebinding in more detail. For now, apply this test: does the function write items = ..., items += ... (on an immutable object), or another statement that binds the name? If so, you need the declaration. If it only calls methods or assigns to an index or attribute, you do not.
The augmented assignment case deserves care. items += [3] on a list is a mutation of the list, but it is also an assignment statement, so Python still rebinds the name afterward. That means the name is local without a global declaration, and the statement fails:
items = []
def extend_items():
items += [3]
extend_items()
# UnboundLocalError: cannot access local variable 'items' where it is not associated with a valueUse items.extend([3]) or items[:] = ... instead, or declare global items.
Placement rules and syntax errors
Python enforces several rules about where and how you write the declaration.
| Mistake | Result |
|---|---|
| Using the name before the `global` statement in the same function | `SyntaxError: name 'count' is used prior to global declaration` |
| Naming a function parameter in a `global` statement | `SyntaxError: name 'x' is parameter and global` |
| Assigning in the same statement, as in `global x = 1` | `SyntaxError` |
The first rule means the declaration should be the first line of the function, after the docstring:
count = 0
def increment():
"""Add one to the module-level counter."""
global count
count += 1
increment()
print(count)
# Output: 1Because the scope of the declaration is the whole function body, you cannot have a local count in one part of a function and the global count in another. The name refers to one thing throughout.
global at module level and in nested functions
A global statement at module level is legal and does nothing useful, because the names are already global. Do not write it.
Inside a nested function, global skips the enclosing function entirely. It does not mean "the next scope outward". It always means the module namespace:
x = "module"
def outer():
x = "enclosing"
def inner():
global x
x = "changed global"
inner()
print(x)
outer()
print(x)
# Output:
# enclosing
# changed globalHere inner changes the module-level x, and outer's own x is untouched. To rebind a name in an enclosing function you need nonlocal, which a later chapter covers.
Global means module-wide, not program-wide
Each module has its own global namespace. A function's globals are those of the module where the function was defined, not of the module that calls it. If counter.py defines increment() with global count, calling it from main.py changes counter.count, not a count in main.py.
This also affects imports. After from counter import count, the name count in your module is a separate binding to the object that existed at import time. If counter.increment() later rebinds counter.count, your imported copy still refers to the old object. Access the value through the module (import counter, then counter.count) if you need to see updates.
Why globals cause trouble
The global statement is sometimes the right tool, for example for a small script or a module-level cache. It has costs:
- Hidden inputs and outputs. A function's behavior depends on state that does not appear in its signature.
- Harder tests. Each test must reset the global, or tests affect each other depending on their order.
- Thread and reentrancy hazards. Read-modify-write on a global, such as
count += 1, is not atomic across threads. - Harder reading. A reader must search the file for every function that declares the name.
Common alternatives are to return the new value and let the caller store it, to pass state as a parameter, or to keep state in a class instance. A closure with nonlocal is another option. The final chapter of this tutorial returns to these choices.
Summary
- Assignment inside a function creates a local name unless the function declares the name
global. global namemakes every binding operation onnamein that function target the module namespace.- Mutating an object, such as calling
append, never needsglobal. Rebinding the name does. - The declaration must come before any use of the name in that function, and it cannot name a parameter.
- Inside nested functions,
globalrefers to the module, not the enclosing function.
Exercise
The code below raises an error. Explain why, then fix it in two different ways: one using global, and one without any global statement. total = 0 def add(n): total = total + n add(5) print(total)
Show answer
Because add assigns to total, Python treats total as local throughout the function, so the right-hand side reads a local variable that has no value yet, which raises UnboundLocalError. Fix 1: add the line "global total" as the first line of add, so the assignment rebinds the module-level name. Fix 2: make the function pure, for example "def add(total, n): return total + n" and call "total = add(total, 5)" at module level, so the caller rebinds the name.
Exercise
Given the code below, what does it print, and which of the three functions would still behave the same if you removed its global statement? log = [] last = None def record(msg): global log log.append(msg) def setlast(msg): global last last = msg def show(): global log, last print(log, last) record("a") setlast("b") show()
Show answer
It prints ['a'] b. Only the global statements in record and show are unnecessary. record only mutates the list with append and show only reads the names, so neither rebinds a name. set_last assigns to last, so it needs its global statement; without it the assignment would create a local variable and the module-level last would stay None.