gpt4 book ai didi

python - globals() 与 locals() 可变性

转载 作者:太空狗 更新时间:2023-10-30 02:19:32 27 4
gpt4 key购买 nike

在 Python 中,globals() 返回全局符号表的表示,而 locals() 返回本地状态的表示。虽然两者都返回字典,但对 globals() 的更改会在全局符号表中生效,而对 locals() 的更改则无效。

为什么会这样?

最佳答案

函数局部变量在编译时进行了高度优化和确定,CPython 建立在无法在运行时动态更改已知局部变量的基础上。

解码函数字节码时可以看到:

>>> import dis
>>> def foo():
... a = 'bar'
... return a + 'baz'
...
>>> dis.dis(foo)
2 0 LOAD_CONST 1 ('bar')
3 STORE_FAST 0 (a)

3 6 LOAD_FAST 0 (a)
9 LOAD_CONST 2 ('baz')
12 BINARY_ADD
13 RETURN_VALUE

LOAD_FASTSTORE_FAST操作码使用 索引 来加载和存储变量,因为在框架上,局部变量是作为数组实现的。访问数组比使用哈希表(字典)更快,例如用于全局命名空间。

locals() 函数在函数中使用时,会返回此数组的反射 作为字典。更改 locals() 字典不会将其反射(reflect)回数组中。

在 Python 2 中,如果您在代码中使用 exec 语句,则优化(部分)被破坏; Python 使用较慢的 LOAD_NAME opcode在这种情况下:

>>> def bar(code):
... exec code
... return a + 'baz'
...
>>> dis.dis(bar)
2 0 LOAD_FAST 0 (code)
3 LOAD_CONST 0 (None)
6 DUP_TOP
7 EXEC_STMT

3 8 LOAD_NAME 0 (a)
11 LOAD_CONST 1 ('baz')
14 BINARY_ADD
15 RETURN_VALUE

另见 bug report against Python 3其中 exec()(Py3 中的函数)不再允许您设置本地名称:

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 - globals() 与 locals() 可变性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29083659/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com