如果我评论了baz = 4
中的声明if False:
阻止我收到消息NameError: name 'baz' is not defined
否则我收到消息NameError: free variable 'baz' referenced before assignment in enclosing scope
我在 python 中运行Python 3.7.2+
def foo():
def bar():
return baz + 1
if False:
baz = 4
pass
return bar()
foo()
我希望总能收到消息NameError: name 'baz' is not defined
就好像我评论了baz = 4
因为baz = 4
语句从未执行,但实际消息是NameError: free variable 'baz' referenced before assignment in enclosing scope
变量baz
从未被分配,但根据代码,它存在于本地命名空间中。因此,有一个为其保留的条目,因此它不是“未定义”,而是“未分配”。
让我们扩展一下你的例子:
def foo(b):
def bar(): return baz
if b: baz = 4
return bar, locals()
并使用它:
>>> a, b = foo(0)
>>> c, d = foo(1)
>>> a
<function foo.<locals>.bar at 0x000002320BA6A0D0>
>>> b
{'bar': <function foo.<locals>.bar at 0x000002320BA6A0D0>, 'b': 0}
>>> c
<function foo.<locals>.bar at 0x000002320BA6A268>
>>> d
{'bar': <function foo.<locals>.bar at 0x000002320BA6A268>, 'b': 1, 'baz': 4}
>>> a.__closure__
(<cell at 0x000002320BA3E9A8: empty>,)
>>> c.__closure__
(<cell at 0x000002320BA3E948: int object at 0x000000006E2C6140>,)
>>> a.__closure__[0].cell_contents
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Cell is empty
>>> c.__closure__[0].cell_contents
4
>>> foo.__code__.co_cellvars
('baz',)
这里我们看到了区别:在第一种情况下,闭包中的单元格保持为空,在第二种情况下,它包含一个 int 对象(即 4)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)