What are nonlocal variables? If this is something that you have been confused about, you are at the right place. This post will give you detailed information about the usage of nonlocal variables, and how they are different from local and global variables.
Nonlocal variables refer to those variables which can neither be in the local scope nor in the global scope. They are usually used in nested methods, wherein the requirement is that the object shouldn't belong to the inner function's scope, hence you define it in the outer function and use it inside the inner function as a nonlocal variable.
Basically, their local scope wouldn't be defined. The keyword nonlocal
is used to indicate that a variable or object is in the nonlocal scope. In short, it helps assign values to variables or objects in a non-global scope
Time for an example:
The below example uses the keyword nonlocal
to indicate the scope of the variable. When the outer_function
is called, and the nested function inner_function
is called, the value of my_str
remains the same since the code of inner_function
is inside that of outer_function
.
def outer_function():
my_str = "local"
def inner_function():
nonlocal my_str
my_str = "nonlocal"
print("inner variable:", my_str)
inner_function()
print("outer variable:", my_str)
outer_function()
Output:
inner variable: nonlocal
outer variable: nonlocal
Can I create a nonlocal variable without using the keyword?
Yes it is absolutely possible. The below code indicates that the nonlocal variable inside the nested function doesn't belong to the function_two
(which is an inner/nested function). The nonlocal
keyword helps variables inside the nested method refer to the most recently (or just before) bound variables/objects in the nearest namespace, which isn't a global value.
Time for an example:
def function_one():
my_str = "Studytonight"
# nested inner function
def function_two():
my_str = "Hello Studytonight"
# calling inner function
function_two()
return my_str
print(function_one())
Output:
Studytonight
Will changes made to nonlocal variables reflect somewhere?
Yes, it reflects as a change in the local variable.
Time for an example
def outer_function():
my_str = "local"
def inner_function():
nonlocal my_str
my_str = "nonlocal"
print("inner variable:", my_str)
inner_function()
print("outer variable:", my_str)
my_str = "Not nonlocal"
print("outer variable:", my_str)
outer_function()
Output:
inner variable: nonlocal
outer variable: nonlocal
outer variable: Not nonlocal
Conclusion:
In this post, we understood how the nonlocal
keyword can be used with objects, and how it differs from local variables. Don't forget to run the code on your IDE and understand the concepts in and out.
You may also like: