What is the difference between the global and nonlocal keywords in Python?
global makes a name inside a function refer to the module-level variable. nonlocal makes it refer to a variable in the nearest enclosing function. Both are needed only when you assign to the name, not when you just read it.
Explain it simply
Without these keywords, assigning to a name inside a function creates a fresh local one, like writing in your own notebook. global says "use the notice board of the whole school". nonlocal says "use the notebook of the class I am nested inside".
Example
count = 0
def bump():
global count
count += 1
bump(); bump()
print(count) # Output: 2
def make_counter():
n = 0
def inc():
nonlocal n
n += 1
return n
return inc
c = make_counter()
print(c(), c(), c()) # Output: 1 2 3nonlocal is what makes closures able to keep and update state between calls. It cannot reach module-level names, and the target must already exist in an enclosing function.
What to say in the interview
"global binds a name to the module scope, nonlocal to the nearest enclosing function scope. I only need them for assignment; reading outer variables works automatically. I try to avoid global state and prefer passing arguments and returning values."
Common mistakes
- Using
nonlocalfor a module-level variable, which is a SyntaxError.