locals
是一个返回本地值字典的内置函数。文档说:
Warning
The contents of this dictionary should not be modified; changes may not affect the values of local variables used by the interpreter.
不幸的是,exec在Python 3.0中也有同样的问题。有什么办法解决这个问题吗?
用例
考虑:
@depends("a", "b", "c", "d", "e", "f")
def test():
put_into_locals(test.dependencies)
depends 将其参数中提供的字符串存储在列表 test.dependences
中。这些字符串是字典 d
中的键。我希望能够编写 put_into_locals
以便我们可以从 d
中提取值并将它们放入本地。这可能吗?
最佳答案
我刚刚测试了 exec,它可以在 Python 2.6.2 中运行
>>> def test():
... exec "a = 5"
... print a
...
>>> test()
5
如果您使用的是 Python 3.x,它不再起作用,因为局部变量在运行时被优化为数组,而不是使用字典。
当 Python 检测到“exec 语句”时,它会强制 Python 将本地存储从数组切换到字典。然而,由于“exec”是 Python 3.x 中的一个函数,编译器无法做出这种区分,因为用户可能会执行类似“exec = 123”的操作。
http://bugs.python.org/issue4831
To modify the locals of a function on the fly is not possible without several consequences: normally, function locals are not stored in a dictionary, but an array, whose indices are determined at compile time from the known locales. This collides at least with new locals added by exec. The old exec statement circumvented this, because the compiler knew that if an exec without globals/locals args occurred in a function, that namespace would be "unoptimized", i.e. not using the locals array. Since exec() is now a normal function, the compiler does not know what "exec" may be bound to, and therefore can not treat is specially.
关于python - 有什么方法可以修改本地人字典吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1450275/