编程语言
首页 > 编程语言> > python – 任何修改本地词典的方法?

python – 任何修改本地词典的方法?

作者:互联网

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)

依赖于将其参数中提供的字符串存储在列表test.dependences中.这些字符串是字典d中的键.我希望能够编写put_into_locals,以便我们可以从d中提取值并将它们放入本地.这可能吗?

解决方法:

我刚刚测试了exec,它适用于Python 2.6.2

>>> def test():
...     exec "a = 5"
...     print a
...
>>> test()
5

如果您使用的是Python 3.x,则它不再起作用,因为locals在运行时被优化为数组,而不是使用字典.

当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,local-variables
来源: https://codeday.me/bug/20190916/1807060.html