Python global and nonlocalThis Python page compares global and nonlocal variables. These keywords change how variables are referenced in methods.
Global, nonlocal. Variable names are sometimes conflicting. In a method, an identifier may reference a local variable or a global variable. The global and nonlocal keywords indicate which variable is being referenced.
uses the global keyword. 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.
Python program that uses global
# Change "value" to mean the global variable.
# ... The assignment will be local without "global."
value = 100
value = 0
# The value has been changed to 100.
Nonlocal is similar in meaning to global. But it 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.
Python program that uses nonlocal
# In nested method, reference nonlocal variable.
value = 100
# Set local.
value = 10
# Local variable reflects nonlocal change.
# Call method.
I was interested in why these keywords were needed. They tend to make Python programs more complex and, in my opinion, ugly. Nonlocal was added to make functions nest better—so they are more easily moved or pasted.
Without nonlocal: There was no way to avoid naming conflicts between locals and enclosing methods. Global was not sufficient.
Quote: But in Python, though functions are usually defined at the top level, a function definition can be executed anywhere. This... yielded inconsistencies that were surprising to some programmers.PEP 3104 Access to Names in Outer Scopes: python.org
Summary. Global and nonlocal are not needed in many (probably most) Python programs. But, when needed, they make methods conflict less with enclosing methods or the global scope. They make the syntax, however, more complex.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to email@example.com.