这个问题在这里已经有了答案:
Why is it bad idea to modify locals in python?
(5 个回答)
5年前关闭。
为什么下面不是在函数内部工作而是在外部工作?
def foo():
common = {'abc' : 'xyz'}
print(locals())
locals().update(common)
print(locals(),abc)
foo()
错误:NameError:未定义全局名称“abc”
如果我在函数外运行它,它会起作用
common = {'abc' : 'xyz'}
print(locals())
locals().update(common)
print(locals(),abc)
最佳答案
Note The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.
所以它不起作用,因为它不打算工作。但是现在要回答您的问题,它在全局范围内有效,因为修改了
globals
是可能的,globals documentation没有说明“这 [...] 不应该被修改”。而且,显然,当您处于全局范围内时, global 是 locals:
>>> globals() is locals()
True
所以你正在修改全局变量,这是允许的。
关于Python 本地更新不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37600997/