Python global and nonlocal

Use global and nonlocal variables. Indicate 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.

This program 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 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) Output 100

Nonlocal. 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 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() Output 100

Discussion. 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:

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.Built-ins
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to