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.
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.
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.
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
I was interested in why these keywords were needed. They tend to make Python programs more complex and (in my opinion) ugly.
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.