Python 3.0+Functionsterm
global / nonlocal
scope
global declares a variable from the global namespace. nonlocal — one from an enclosing function (not the global scope).
Syntax
global x
nonlocal y
You only need these to rebind: reading a global, or mutating a mutable object in place (list.append), works without global. nonlocal requires the variable to already exist in an enclosing function — it can't create a new one and won't reach the global scope.
Examples
counter = 0
def increment():
global counter
counter += 1
increment()
print(counter) # → 1
def make_counter():
count = 0
def inc():
nonlocal count
count += 1
return count
return inc
c = make_counter()
print(c(), c(), c()) # → 1 2 3
total = 0
def add(x):
global total
total += x
add(5); add(3)
print(total) # → 8
def outer():
x = 0
def middle():
nonlocal x
x = 10
def inner():
nonlocal x
x += 1
inner()
middle()
return x
print(outer()) # → 11
# global можно объявить несколько переменных
a = b = 0
def reset():
global a, b
a = b = 1
reset()
print(a, b) # → 1 1
def acc():
s = 0
def add(n):
nonlocal s
s += n
return s
return add
f = acc()
print(f(3), f(4)) # → 3 7
See also
Open in the full glossarydocs.python.orgReport an inaccuracy