# Python: variable scope

2022-02-02 14:15:01 Ice sky

# Variable action rules

stay Python in , Variable action , That is, the search of variables , follow LEGB The rules ：
L o c a l → E n c l o s e d → G l o b l a → B u i l t − i n Local\rightarrow Enclosed\rightarrow Globla\rightarrow Built-in
among ：

• Local： Local space
• Enclosed： Closure space
• Global： Code file global space
• Built-in： Built in space , Outermost layer

stay Python Two variable scope keywords in ：

• global
• nonlocal

## global

If we do this in a function ：

x = 1
def func1():
x = x + 1 # error
print(x)


An error will be thrown ：

Error: reference before assignment


For global variables , In local space, if and only if variable variables （ for example list） You can modify , The immutable variable will report an error , When ：

y = []

def func2():
#  Variable type
y.append(1)
print(y) # output [1]


If you want to modify immutable variables , You need to use global Keyword specifies the variable space ：

x = 1
def func3():
global x = x + 1
print(x) # output 2


## nonlocal

nonlocal and global similar , however global Is to directly find global variables , and nonlocal Is to find out from the current local space , For example, the following nested function ：

message = 'global'

def func():
message = 'nonlocal'
def func_sub1():
global message
print(message)
def func_sub2():
nonlocal message
print(message)

func_sub1()
func_sub2()

func()


The output will be ：

global
nonlocal


You can see ,nonlocal What is found is... In the variable space outside the nested function 'messsage'.

# Example

message = 'global'

def TestVariableScope():

message = 'nonlocal'

def _local():
message = 'local'
print(message)

def _nonlocal():
nonlocal message
print(message)

def _global():
global message
print(message)

_local()
_nonlocal()
_global()

def main():
TestVariableScope()

if __name__ == '__main__':
main()


Output ：

local
nonlocal
global