python – 任何修改本地词典的方法?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 任何修改本地词典的方法?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1539字,纯文字阅读大概需要3分钟。
内容图文
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 – 任何修改本地词典的方法?全部内容,希望文章能够帮你解决python – 任何修改本地词典的方法?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。