# 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 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.
# In nested method, reference nonlocal variable.
value = 100
# Set local.
value = 10
# Local variable reflects nonlocal change.
# Call method.
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).