1Global
The global statement and its nonlocal cousin are the only things that are remotely like declaration statements in Python. They arenot type or size declarations; they arenamespace declarations. The global statement tells Python that a function plans to change one or more global names.
• Global names are variables assigned at the top level of the enclosing module file.
• Global names must be declared only if they are assigned within a function.
• Global names may be referenced within a function without being declared.
In otherWords, global allows us to change names that live outside a def at the top level of a module file.
2Example
The global statement consists of the keyword global, followed by one or more names separated by commas.
X = 88#Global Xdeffunc():globalX
X= 99#Global X: outside deffunc()PRint(X)#Prints 99
y, z = 1, 2#Global variables in moduledefall_global():globalx#Declare globals assignedx = y + z#No need to declare y, z: LEGB rule
x, y, and z are all globals inside the function all_global.y and z are global because they aren’t assigned in the function; x is global because it was listed in aglobal statement to map it to the module’s scope explicitly. Without the global here, x would be considered local by virtue of the assignment.
3accessglobals
#thismod.pyvar = 99#Global variable == module attributedeflocal():
var= 0#Change local vardefglob1():globalvar#Declare global (normal)var += 1#Change global vardefglob2():
var= 0#Change local varimportthismod#Import myselfthismod.var += 1#Change global vardefglob3():
var= 0#Change local varimportsys#Import system tableglob = sys.modules['thismod']#Get module object (or use __name__)glob.var += 1#Change global vardeftest():print(var)
local();print(var)
glob1();print(var)
glob2();print(var)
glob3()print(var)
run and get results
>>>importthismod>>>thismod.test()99
99
100
101
102