global and nonlocal
global lets a function change a variable defined at the top of the file; nonlocal lets an inner function change one from the outer function.
global name
nonlocal nameA function can read variables from outside it. But as soon as you assign to a name inside a function, Python treats it as a new local variable that exists only in that call. global counter tells Python: "when I assign to counter here, change the one at the top level of the file".
nonlocal does the same for nested functions: an inner function can change a variable of the function around it. This is how small closures, such as counters, keep their state between calls.
Use both sparingly. A function that returns a new value is easier to test and understand than one that quietly changes something outside itself.
Examples
1Reading works without global
tax_rate = 0.2
def with_tax(price):
return price * (1 + tax_rate)
print(with_tax(50))60.0
2Changing needs global
visits = 0
def record_visit():
global visits
visits += 1
record_visit()
record_visit()
print("Visits:", visits)Visits: 2
3Without global you get an error
score = 10
def add_point():
try:
score += 1
except UnboundLocalError:
print("UnboundLocalError: score is treated as local")
add_point()
print(score)UnboundLocalError: score is treated as local 10
Because the function assigns to score, Python treats it as local, and it has no value yet when += 1 reads it.
4nonlocal in a closure
def make_counter():
count = 0
def step():
nonlocal count
count += 1
return count
return step
ticket = make_counter()
print(ticket(), ticket(), ticket())
other = make_counter()
print(other())1 2 3 1
Each call to make_counter() creates its own count, so the two counters do not interfere.
Common mistakes
Using global instead of returning a value
Functions that change globals are hard to follow. Pass the value in and return the new one.
def add_visit(visits):
return visits + 1
visits = 0
visits = add_visit(visits)
visits = add_visit(visits)
print(visits)2
Thinking global is needed to change a list's contents
Calling a method such as cart.append(x) changes the list without assigning to the name, so no global is needed. You only need it to point the name at a new object (cart = []).
Questions people ask
What is the difference between global and nonlocal?
global refers to the module's top level. nonlocal refers to the nearest enclosing function. nonlocal cannot reach module-level names.
Why do I get UnboundLocalError?
You assigned to a name inside a function, so Python treats it as local everywhere in that function, even on lines before the assignment. Add global or nonlocal, or pass the value in.
Are global variables bad?
Constants at the top of a file (like TAX_RATE = 0.2) are fine. Changing globals from many functions is what makes code hard to maintain.