I'm learning the concepts of programming languages.
I found the terminology "nonlocal" in python syntax.
What is the meaning of nonlocal in python?
I'm learning the concepts of programming languages.
I found the terminology "nonlocal" in python syntax.
What is the meaning of nonlocal in python?
The nonlocal variables are present in a nested block. A keyword nonlocal is used and the value from the nearest enclosing block is taken. For example:
def outer():
x = "local"
def inner():
nonlocal x
x = "nonlocal"
print("inner:", x)
inner()
print("outer:", x)
The output will be "nonlocal" both the times as the value of x has been changed by the inner function.
"nonlocal" means that a variable is "neither local or global", i.e, the variable is from an enclosing namespace (typically from an outer function of a nested function).
An important difference between nonlocal and global is that a nonlocal variable must have been already bound in the enclosing namespace (otherwise an syntaxError will be raised) while a global declaration in a local scope does not require the variable is pre-bound (it will create a new binding in the global namespace if the variable is not pre-bound).
nonlocal foo
in inner()
can access the non-local variable foo = 10
in middle()
but not the non-local variable foo = 5
in outer()
or the global variable foo = 0
outside outer()
as shown below:
foo = 0 # <- ✖
def outer():
foo = 5 # <- ✖
def middle():
foo = 10 # <- 〇
def inner():
nonlocal foo # Here
foo += 1
print(foo) # 11
inner()
middle()
outer()
global foo
in inner()
can access the global variable foo = 0
outside outer()
but not the non-local variable foo = 5
in outer()
and middle()
as shown below:
foo = 0 # <- 〇
def outer():
foo = 5 # <- ✖
def middle():
foo = 10 # <- ✖
def inner():
global foo # Here
foo += 1
print(foo) # 1
inner()
middle()
outer()
From the documentation about nonlocal statements:
The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope. This is important because the default behavior for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.
Names listed in a nonlocal statement, unlike to those listed in a global statement, must refer to pre-existing bindings in an enclosing scope (the scope in which a new binding should be created cannot be determined unambiguously).
Names listed in a nonlocal statement must not collide with pre- existing bindings in the local scope
global x
def outer():
x="global"
def inner():
nonlocal x
x="nonlocal"
def inner2():
x="local"
inner2()
print(x)
inner()
print(x)
outer()
Output:
global
nonlocal
© 2022 - 2025 — McMap. All rights reserved.