First, I fully understand what global
statement means and how to use.
Now, let's look at this:
x = 100
def f():
global x
global xxx
x = 99
return x
print(f())
# >>> 99
print(x)
# >>> 99
You can see that by using global x
, I successfully changed the value of x in the global environment.
But xxx
does not exist at all, why am I allowed to global it and it won't even bring any error even if the function is executed?
global x
does not define, declare, or otherwise createx
. It simply states that if and whenx
is assigned to in the current function scope (whether that assignment comes before or after theglobal
statement, which is why it is strongly recommended thatglobal
statements be used at the beginning of the function), the assignment is made to a global variable of that name, not a local variable. The actual creation is still the job of an actual assignment.Put another way,
global
doesn't generate any byte code by itself; it simply modifies what byte code other assignment statements might generate. Consider these two functions:The only difference in the byte code for these two functions is that
f
useSTORE_GOBAL
as a result of theglobal
statement, whileg
usesSTORE_FAST
.If you were to add an "unused"
global
statement, such as inthe resulting byte code is indistinguishable from
g
: