ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-09-16 07:55:01  阅读:182  来源: 互联网

标签:python local-variables


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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有