Why am I able to global a non-existing variable in python

我怕爱的太早我们不能终老 提交于 2019-12-07 17:29:41

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/51288447/why-am-i-able-to-global-a-non-existing-variable-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!