结果locals()
函数内部的调用不能用于使用您的方法实际更新局部变量。这文档 https://docs.python.org/3/library/functions.html#locals明确表示:
locals()
更新并返回表示当前本地符号表的字典。自由变量由以下方式返回locals()
当它在功能块中调用时,而不是在类块中调用时。请注意,在模块级别,locals()
and globals()
是同一个字典。
注意 不得修改本词典的内容;更改可能不会影响解释器使用的局部变量和自由变量的值。
The reason why you cannot update locals using this method is that they are heavily optimised within the CPython source code(a). When you call locals()
, it actually builds a dictionary (the "update and return" bit) based on these heavily optimised structures and that is what you get.
为该字典编写一个新键是not反射回actual locals.
我相信globals()
返回值does允许使用此方法进行更新,因为它已经是一本字典,它只是为您提供对它的引用,而不是副本。这就是为什么您的代码在函数之外工作的原因(请参阅上面的条款locals()
and globals()
在这种情况下是同一件事)。
根据记忆,Python 2 允许你做类似的事情exec "answer = 42"
然后would影响当地人。但是,正如print
,这在 Python 3 中从语句更改为库调用,因此执行引擎实际上不知道它在幕后做了什么,这意味着它无法神奇地将局部变量与exec("answer = 42")
.
我想有人could请求将此作为一项功能,因为它会使动态编程变得更容易一些。我不知道它是否能通过挑战,因为事实上你可以提供你的own locals
字典到exec()
意味着您已经有办法检测由任意代码绑定的变量。他们只会在一个separate字典而不是实际的当地人区域。
(a) Access to locals is via known indexes into the stack-frame local variable area, computed at compile time and embedded into the actual bypte code. Being able to add/change variables dynamically would break this optimisation.
这个问题是作为issue https://bugs.python.org/issue4831早在 2009 年初,结果是在不损失大量性能的情况下太困难了。