Member-only story
Have you heard of the nonlocal keyword in Python?
When working with nested functions in Python, you might encounter situations where you need to modify a variable defined in an enclosing scope. This is where the nonlocal
keyword comes into play. In this post, we’ll explore what nonlocal
is, how it works, and when to use it.
Read for free: https://allwin-raju.medium.com/have-you-heard-of-the-nonlocal-keyword-in-python-8b44e6921b66?sk=c338aa953d55435fcdca99ec1a396793
What Is nonlocal?
The nonlocal
statement is used to indicate that a variable exists in an enclosing scope (but not the global scope) and should be rebound in that scope. It allows you to modify the value of a variable from a parent function inside a nested function.
Syntax
nonlocal variable_name
This simple statement tells Python to look for the variable in the nearest enclosing scope that is not the global scope.
Why do we need nonlocal?
Here’s an example to demonstrate its usage:
def outer_function():
x = 10 # This variable is in the enclosing scope of inner_function
def inner_function():
nonlocal x
x += 1
print("Inner x:", x)
inner_function()
print("Outer x:", x)…