Rebind Names with global and nonlocal
Core idea
Use global name to make assignments to that name target the module namespace. Use nonlocal name inside a nested function to target an existing binding in an enclosing function, not the module. Both declarations apply to the code block and should precede use of the name.
count = 2def add(): global count count += 1add()print(count)The assignment modifies the module binding, so the caller sees 3.
Update an enclosing counter
def batch(): count = 0 def add(): nonlocal count count += 2 add() add() return countprint(batch())Both calls rebind the same enclosing count. No module-level count is needed.
Mutation needs no rebinding declaration
labels = []def add(): labels.append("A")add()print(labels)append changes the existing list, not the binding of labels.
Common mistake
nonlocal cannot create a missing enclosing binding; using it without such a binding is a SyntaxError. Prefer parameters and return values when shared state is unnecessary.
Practice
Make batch add 3 each time. Predict what happens if nonlocal is removed, then run that intentional error separately.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Choose the intended rebinding scope
Check your understanding of global and nonlocal.
What is printed?
n = 5def f(): global n n += 3f()print(n)What is printed?
def outer(): n = 4 def add(): nonlocal n n += 2 add() return nprint(outer())What is printed?
items = []def add(): items.append(3)add()print(items)What does nonlocal require?