Nonlocal Statement in Python
The nonlocal statement in Python is a powerful feature that allows a function to modify a variable that is not local to it but is defined in an enclosing function. This is particularly useful when dealing with nested functions, where you might want to modify a variable from an outer function within an inner function.
Overview
The nonlocal statement is used to refer to a variable in the closest enclosing scope that is not global. This means that it allows a function to access and modify variables that are defined in an enclosing function, but not at the global level. This is different from the global statement, which is used to refer to variables at the top level of the module.
Example Usage
Consider the following example, which demonstrates the use of the nonlocal statement:
Listing 9.1 File nonlocal.py
g_var = 0 #A
nl_var = 0 #B
print("top level-> g_var: {0} nl_var: {1}".format(g_var, nl_var))
def test():
nl_var = 2 #C
print("in test-> g_var: {0} nl_var: {1}".format(g_var, nl_var))
def inner_test():
global g_var #D
nonlocal nl_var #E
g_var = 1
nl_var = 4
print("in inner_test-> g_var: {0} nl_var: {1}".format(g_var,
nl_var))
inner_test()
print("in test-> g_var: {0} nl_var: {1}".format(g_var, nl_var))
test()
print("top level-> g_var: {0} nl_var: {1}".format(g_var, nl_var))
#A g_var in global scope.
#B nl_var in global scope.
#C nl_var in test (not global).
#D use of global makes g_var in inner_test bind to top level g_var.
#E use of nonlocal makes nl_var bind to nl_var in test.
Explanation
-
Global Variable (
g_var): The variableg_varis defined at the global scope. Theglobalstatement ininner_testmakesg_varininner_testrefer to this top-levelg_var. Wheng_varis modified ininner_test, it affects the globalg_var. -
Nonlocal Variable (
nl_var): The variablenl_varis defined in thetestfunction. Thenonlocalstatement ininner_testmakesnl_varininner_testrefer to thenl_varintest. This allowsinner_testto modifynl_varin thetestfunction.
Output
The output of the above code will be:
top level-> g_var: 0 nl_var: 0
in test-> g_var: 0 nl_var: 2
in inner_test-> g_var: 1 nl_var: 4
in test-> g_var: 0 nl_var: 4
top level-> g_var: 1 nl_var: 0
This output shows how the global and nonlocal statements affect the variables in different scopes. The global statement allows inner_test to modify the global g_var, while the nonlocal statement allows it to modify nl_var in the test function.
FAQ (Frequently asked questions)
What is the purpose of the nonlocal statement in Python?
How does the nonlocal statement work in nested functions?
Can the nonlocal statement be used to modify global variables?
What does the nonlocal statement do in the provided code example?
How does the global statement affect variables in the code example?
What is the initial value of 'nl_var' in the global scope?
What changes occur to 'g_var' and 'nl_var' after calling 'inner_test'?