global / nonlocal keyword on in Python
1. Python variable scope
Python variable scope can be divided into the following four categories:
- Local: local scope
- Enclosing: closure function outside the scope function
- Global: global scope
- Built-in: Built-Scope
By-level lookup to find variables (L, E, G, B ). It is worth noting that, Python do not have block-level scope , but a similar function scope form.
2. Python variable definitions
Python will be defined directly without having to declare a variable, but in the following example:
a = 1
b = 99
def print_two(x, y):
print(x)
print(y)
def function_test():
a = 2
print_two(a, b)
function_test()
print_two(a, b)
Output runtime:
2
99
1
99
It found that in the internal scope, can refer directly to the value of the variable domain global role, but can not be directly modified assignment operation.
3. global keyword
As shown in the example:
a = 1
b = 99
def print_two(x, y):
print(x)
print(y)
def function_test():
global a
a = 2
print_two(a, b)
function_test()
print_two(a, b)
operation result:
2
99
2
99
The role of global keyword is in the local scope, use global variables. Without modification involves global variables (simply reference), you may not use the global keyword.
4. nonlocal keyword
Sample code:
a = 1
def test():
a = 2
def test1():
a = 3
def test2():
nonlocal a
a = 4
print(a)
test2()
print(a)
test1()
print(a)
test()
print(a)
operation result:
4
4
2
1
That nonlocal keyword that the outer layer (non-global) variables in local scope.
5. With regard to global variables
In Python, an alternative to using global variables is to use a separate global.py
file stores all global variables can be referenced and modified.