What if you could fix tricky bugs by simply telling Python which variable to change inside nested functions?
Why Nonlocal keyword in Python? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine you have a small box inside a bigger box, and you want to change something inside the smaller box from outside it. Without a special way, you can only change things in the smallest box or the biggest box, but not the middle one. This is like trying to change a variable inside a nested function without a special keyword.
Without the nonlocal keyword, changing a variable inside a nested function creates a new local copy instead of updating the variable in the outer function. This leads to confusion and bugs because the outer variable stays unchanged, making your code behave unexpectedly and harder to fix.
The nonlocal keyword lets you tell Python to use the variable from the nearest outer function, not create a new one. This way, you can easily update variables in nested functions, keeping your code clear and working as you expect.
def outer(): x = 5 def inner(): x = 10 # This creates a new local x, outer x stays 5 inner() print(x) # prints 5
def outer(): x = 5 def inner(): nonlocal x x = 10 # updates outer x inner() print(x) # prints 10
It enables you to cleanly and safely modify variables in outer functions from inside nested functions, making your code easier to write and understand.
Think of a game where you have a score counter inside a main game function, and a smaller function inside it updates the score. Using nonlocal lets the smaller function change the main score directly without confusion.
Without nonlocal, nested functions can't change outer variables properly.
nonlocal tells Python to use the nearest outer variable, not create a new one.
This makes nested function code clearer and less error-prone.
Practice
nonlocal keyword do in Python?Solution
Step 1: Understand variable scopes
Variables inside a function are local by default, and inner functions cannot change outer variables unless specified.Step 2: Role of
Thenonlocalnonlocalkeyword allows the inner function to access and modify variables from the nearest enclosing function scope.Final Answer:
Allows an inner function to modify a variable from its outer function. -> Option BQuick Check:
nonlocal changes outer function variable = A [OK]
- Confusing nonlocal with global keyword
- Thinking nonlocal creates new variables
- Assuming nonlocal works outside functions
nonlocal inside a nested function?Solution
Step 1: Recall the syntax for nonlocal
The keywordnonlocalis followed by the variable name to indicate it refers to an outer function's variable.Step 2: Compare options
Only nonlocal variable_name uses the correct keyword and syntax:nonlocal variable_name.Final Answer:
nonlocal variable_name -> Option DQuick Check:
Correct nonlocal syntax = C [OK]
- Using 'global' instead of 'nonlocal'
- Writing 'local' or 'outer' which are invalid keywords
- Forgetting to write variable name after nonlocal
def outer():
x = 5
def inner():
nonlocal x
x = 10
inner()
return x
print(outer())Solution
Step 1: Trace variable assignment
Variablexis set to 5 inouter(). The inner function declaresnonlocal xand setsx = 10.Step 2: Effect of nonlocal on
Thexnonlocalkeyword allowsinner()to modifyxinouter(). So after callinginner(),xbecomes 10.Final Answer:
10 -> Option AQuick Check:
nonlocal changes outer x to 10 = D [OK]
- Thinking x remains 5 because inner is separate
- Expecting a syntax error for nonlocal usage
- Assuming inner creates a new local x
def counter():
count = 0
def increment():
count = count + 1
return count
return increment()
print(counter())Solution
Step 1: Identify variable scope issue
Insideincrement(),count = count + 1tries to read and writecount. Withoutnonlocal, Python treatscountas local, but it is used before assignment.Step 2: Fix with
Addingnonlocalnonlocal counttells Python to use thecountfromcounter(), allowing modification.Final Answer:
Missing 'nonlocal count' inside increment() -> Option CQuick Check:
Modify outer variable needs nonlocal = A [OK]
- Using global instead of nonlocal
- Ignoring variable scope causing UnboundLocalError
- Returning count without incrementing properly
def make_accumulator():
total = 0
def add(value):
nonlocal total
total += value
return total
return add
acc = make_accumulator()
print(acc(5))
print(acc(3))
print(acc(-2))What is the output of this code?
Solution
Step 1: Understand closure with nonlocal
The functionmake_accumulator()returnsadd, which rememberstotal. Thenonlocal totalletsaddupdatetotaleach call.Step 2: Trace calls to
First call: total=0+5=5, prints 5.acc
Second call: total=5+3=8, prints 8.
Third call: total=8+(-2)=6, prints 6.Final Answer:
5 8 6 -> Option AQuick Check:
Accumulator sums values using nonlocal total = B [OK]
- Expecting total to reset each call
- Confusing nonlocal with global
- Thinking output is separate values, not cumulative
