Reputation: 1742
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?
Upvotes: 3
Views: 657
Reputation: 531155
global x
does not define, declare, or otherwise create x
. It simply states that if and when x
is assigned to in the current function scope (whether that assignment comes before or after the global
statement, which is why it is strongly recommended that global
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:
def f():
global x
x = 99
def g():
x = 99
The only difference in the byte code for these two functions is that f
use STORE_GOBAL
as a result of the global
statement, while g
uses STORE_FAST
.
>>> dis.dis(f)
5 0 LOAD_CONST 1 (99)
3 STORE_GLOBAL 0 (x)
6 LOAD_CONST 0 (None)
9 RETURN_VALUE
>>> dis.dis(g)
8 0 LOAD_CONST 1 (99)
3 STORE_FAST 0 (x)
6 LOAD_CONST 0 (None)
9 RETURN_VALUE
If you were to add an "unused" global
statement, such as in
def h():
global xxx
x = 99
the resulting byte code is indistinguishable from g
:
>>> dis.dis(h)
3 0 LOAD_CONST 1 (99)
2 STORE_FAST 0 (x)
4 LOAD_CONST 0 (None)
6 RETURN_VALUE
Upvotes: 11