'global' 在 if 语句下如何表现?

How does 'global' behave under an if statement?

在我的程序中,我只在某些情况下需要一个全局变量。说它看起来像这样:

a = 0
def aa(p):
    if p:
        global a
    a = 1
    print("inside the function " + str(a))


print(a)
aa(False)
print("outside the function " + str(a))

我期待的结果是:

0
inside the function 1
outside the function 0

然而结果是:

0
inside the function 1
outside the function 1

所以,我在想,"Okay maybe the Python compiler makes the variable global whenever it sees the 'global' keyword no matter where it is located"。 Python 是这样处理全局变量的吗?我是不是误会了?

是的,您理解正确。

global 语句不是在运行时计算的东西。它实际上是解析器指令,本质上告诉它把所有列出的标识符(这里的a)视为指的是全局范围.来自 the global statement 上的文档:

The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals.

然后它继续说明 global 实际上是一个 指令:

Programmer’s note: global is a directive to the parser.

有条件地使用它没有任何区别:它的存在已经在解析阶段被检测到,因此,为获取名称而生成的字节码已经设置为在全局范围内查看(LOAD/STORE GLOBAL)。

这就是为什么,如果您 dis.dis 一个包含 global 语句的函数,您将看不到 global 的任何相关字节码。使用愚蠢的功能:

from dis import dis
def foo():
    "I'm silly"
    global a  

dis(foo)
  2           0 LOAD_CONST               0 (None)
              2 RETURN_VALUE

没有为 global a 生成任何内容,因为它提供的信息已被使用!