Home
Python
nonlocal and global
Updated Sep 26, 2022
Dot Net Perls
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
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 26, 2022 (edit).
Home
Changes
© 2007-2025 Sam Allen