尽管在全局范围内声明了变量,但我还是收到了 UnboundLocalError。似乎该变量被假定/强制为该特定语句的局部变量。
我不明白为什么 if 语句条件中的变量会被区别对待。谁能解释一下这是怎么回事?
以下片段是我尝试做的事情的简化示例:
In [1]: global mock
... mock = False
...
...
... def foo():
... if not mock:
... # do stuff
... mock = True
...
... # do other stuff
...
...
... foo()
这会抛出一个 UnboundLocalError,尽管在函数声明的正上方声明了全局 bool。
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
<ipython-input-31-540737067cb1> in <module>()
7
8
----> 9 foo()
<ipython-input-31-540737067cb1> in foo()
3
4 def foo():
----> 5 if not mock:
6 mock = True
7
UnboundLocalError: local variable 'mock' referenced before assignment
但是,此代码段按预期运行:
In [2]: mock = False
...
...
... def bar():
... return mock
...
...
... bar()
Out[2]: False
类似地,这个在 if 语句主体中带有变量的片段也按预期运行:
In [3]: mock = False
...
...
... def foobar():
... if True:
... return mock
...
... return True
...
...
... foobar()
Out[3]: False
我在文档 ( https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces ) 中找到了以下关于作用域和命名空间的文章,但我认为它应该根据以下内容按预期工作,
Although scopes are determined statically, they are used dynamically. At any time during execution, there are at least three nested scopes whose namespaces are directly accessible:
- the innermost scope, which is searched first, contains the local names
- the scopes of any enclosing functions, which are searched starting with the nearest enclosing scope, contains non-local, but also non-global names
- the next-to-last scope contains the current module’s global names
- the outermost scope (searched last) is the namespace containing built-in names
我在 Windows 10 上的 Conda 中将 Jupyter 4.4.0 与 Python 3.6.6 和 IPython 6.5.0 一起使用,但我能够使用控制台 IPython 和运行 Python 3.6.0 的 IDLE 3.6.0 GUI 重现此行为。
编辑:不知何故,下面的片段没有受到影响?这似乎与更新同一变量有关。我觉得此时我一定遗漏了一些微不足道的东西。
In [4]: global mock # also works without this line
... mock = False
...
...
... def foo1():
... if not mock:
... return mock
...
... return True
...
...
... foo1()
Out[4]: False
请您参考如下方法:
变量是函数范围的。因为在函数中有一个名称 mock 的赋值,所有对 mock 的引用都被尝试作为“本地”(它们实际上被编译为不同的操作码!)
您可以通过在函数中使用 global mock 来更改它(因此赋值和引用被强制为 global)
def foo():
global mock
if not mock:
mock = true
请注意,在您的第一个示例中,您在模块范围内编写了 global mock —— 这什么都不做:)
直接看反汇编可能更有意义:
>>> import dis
>>> def f():
... if not mock:
... mock = True
...
>>> dis.dis(f)
2 0 LOAD_FAST 0 (mock)
3 POP_JUMP_IF_TRUE 15
3 6 LOAD_GLOBAL 0 (True)
9 STORE_FAST 0 (mock)
12 JUMP_FORWARD 0 (to 15)
>> 15 LOAD_CONST 0 (None)
18 RETURN_VALUE
>>> def g():
... global mock
... if not mock:
... mock = True
...
>>> dis.dis(g)
3 0 LOAD_GLOBAL 0 (mock)
3 POP_JUMP_IF_TRUE 15
4 6 LOAD_GLOBAL 1 (True)
9 STORE_GLOBAL 0 (mock)
12 JUMP_FORWARD 0 (to 15)
>> 15 LOAD_CONST 0 (None)
18 RETURN_VALUE
