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.
函数局部变量在编译时被高度优化和确定,CPython的基础是不能在运行时动态地改变已知的局部变量。在
解码字节码时可以看到:
^{} 和^{} 操作码使用索引来加载和存储变量,因为在帧上,局部变量被实现为数组。访问数组比使用哈希表(字典)更快,例如用于全局命名空间。在
当在函数中使用
locals()
函数时,将返回该数组的一个反射作为字典。更改locals()
字典不会将其反映回数组中。在在Python2中,如果您在代码中使用} opcode :
^{pr2}$exec
语句,那么优化(部分)中断;在这种情况下,Python使用较慢的^{另请参见bug report against Python 3,其中
exec()
(Py3中的函数)不再允许您设置本地名称:相关问题 更多 >
编程相关推荐