Python: locals() 的奇怪行为
Python: Strange behavior of locals()
我在 Python 中遇到内置函数 locals() 的奇怪行为。具体不好解释,请看一段代码:
def Main():
def F(l=locals()): print 'F', id(l), l
a= 100
F()
print '1', id(locals()), locals()
F()
在局部函数 F
中,我将 locals()
分配给 l
作为 enclosure 的默认值。由于 locals()
是 dict
,它的引用被复制到 l
。所以最后三行应该有相同的结果。
然而结果是这样的:
F 139885919456064 {}
1 139885919456064 {'a': 100, 'F': <function F at 0x7f39ba8969b0>}
F 139885919456064 {'a': 100, 'F': <function F at 0x7f39ba8969b0>}
三个print
语句几乎同时被调用,locals()
和l
的id
是一样的,但是第一个l
用在F
没有内容
我不明白为什么会这样。谁能解释这种现象?或者这是一个 known/unknown 错误?
非常感谢!
如果您阅读 locals
函数的 docs,您会看到
Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks.
locals()
不只是 return 局部变量的字典;它还更新字典以反映当前的局部变量值。
我在 Python 中遇到内置函数 locals() 的奇怪行为。具体不好解释,请看一段代码:
def Main():
def F(l=locals()): print 'F', id(l), l
a= 100
F()
print '1', id(locals()), locals()
F()
在局部函数 F
中,我将 locals()
分配给 l
作为 enclosure 的默认值。由于 locals()
是 dict
,它的引用被复制到 l
。所以最后三行应该有相同的结果。
然而结果是这样的:
F 139885919456064 {}
1 139885919456064 {'a': 100, 'F': <function F at 0x7f39ba8969b0>}
F 139885919456064 {'a': 100, 'F': <function F at 0x7f39ba8969b0>}
三个print
语句几乎同时被调用,locals()
和l
的id
是一样的,但是第一个l
用在F
没有内容
我不明白为什么会这样。谁能解释这种现象?或者这是一个 known/unknown 错误?
非常感谢!
如果您阅读 locals
函数的 docs,您会看到
Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks.
locals()
不只是 return 局部变量的字典;它还更新字典以反映当前的局部变量值。