Global, nonlocal. Variable names are sometimes conflicting. In a method, an identifier may reference a local variable or a global variable.
In a program, the global and nonlocal keywords indicate which variable is being referenced. They disambiguate variable references in Python.
Global example. In method(), we use the statement "global value." This means that the identifier "value" refers to the global "value," which is accessed outside the method.
Result The variable is changed to equal 100 in method(). And this is reflected in the global variable at the end of the program.
def method():
# Change "value" to mean the global variable.# ... The assignment will be local without "global."
global value
value = 100
value = 0
method()
# The value has been changed to 100.
print(value)100
Nonlocal takes effect primarily in nested methods. It means "not a global or local variable." So it changes the identifier to refer to an enclosing method's variable.
Here Method2() uses nonlocal to reference the "value" variable from method(). It will never reference a local or a global.
def method():
def method2():
# In nested method, reference nonlocal variable.
nonlocal value
value = 100
# Set local.
value = 10
method2()
# Local variable reflects nonlocal change.
print(value)
# Call method.
method()100
A discussion. I was interested in why these keywords were needed. They tend to make Python programs more complex and (in my opinion) ugly.
And Nonlocal was added to make functions nest better—so they are more easily moved or pasted.
Summary. Global and nonlocal are not needed in many Python programs. But, when needed, they make methods conflict less with enclosing methods or the global scope.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 26, 2022 (edit).