有什么方法可以修改本地字典吗? [英] Any way to modify locals dictionary?

查看:97
本文介绍了有什么方法可以修改本地字典吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

locals是一个内置函数,该函数返回本地值的字典.该文档说:

locals is a built in function that returns a dictionary of local values. The documentation says:

警告

这本词典的内容应该 不可修改;更改可能不会 影响局部变量的值 由口译员使用.

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中也有同样的问题.有什么办法解决这个问题吗?

Unfortunately, exec has the same problem in Python 3.0. Is there any way round this?

用例

考虑:

@depends("a", "b", "c", "d", "e", "f")
def test():
    put_into_locals(test.dependencies)

depends将其自变量中提供的字符串存储在列表test.dependences中.这些字符串是字典d中的键.我希望能够编写put_into_locals,以便我们可以将值从d中拉出并将其放入本地.这可能吗?

depends stores the strings provided in its arguments in a list test.dependences. These strings are keys in a dictionary d. I would like to be able to able to write put_into_locals so that we could pull the values out of d and put them into the locals. Is this possible?

推荐答案

我刚刚测试了exec,它可以在Python 2.6.2中工作

I just tested exec and it works in Python 2.6.2

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

如果您使用的是Python 3.x,它将无法正常工作,因为在运行时将本地变量优化为数组,而不是使用字典.

If you are using Python 3.x, it does not work anymore because locals are optimized as an array at runtime, instead of using a dictionary.

当Python检测到"exec语句"时,它将强制Python将本地存储从数组切换到字典.但是,由于"exec"是Python 3.x中的函数,因此编译器无法进行区分,因为用户可能会执行"exec = 123"之类的事情.

When Python detects the "exec statement", it will force Python to switch local storage from array to dictionary. However since "exec" is a function in Python 3.x, the compiler cannot make this distinction since the user could have done something like "exec = 123".

http://bugs.python.org/issue4831

在以下位置修改函数的局部变量 没有就不可能有苍蝇 几种后果:通常, 函数本机未存储在 字典,但一个数组,其 索引是在编译时确定的 来自已知的语言环境.这相撞 至少添加了新的本地人 执行旧的exec语句 规避了这一点,因为 编译器知道如果一个exec没有 globals/locals args发生在 函数,该名称空间将是 未优化",即不使用 当地人数组.由于exec()现在是 正常功能,编译器不 知道"exec"可能绑定到什么,并且 因此不能特别对待.

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.

这篇关于有什么方法可以修改本地字典吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆