gpt4 book ai didi

python - STORE_NAME 和 STORE_GLOBAL 在主要范围内是等价的吗?

转载 作者:行者123 更新时间:2023-11-28 18:53:18 25 4
gpt4 key购买 nike

我想我对 Python 中的模块命名空间有点困惑。我玩过 Byteplay,这就是我尝试过的:

  1. 我构建了一个等同于 : (byteplay's printcodelist) -> 的操作码列表


    0 LOAD_CONST 3
    1 STORE_NAME a
    2 LOAD_CONST None
    3 RETURN_VALUE

    但是当我那样执行它时:


    exec mycode in t #t is {}
    print 'a' in t #False , but I expected True

    同样的事情发生在我

    import b 
    'a' in b.__dict__ #False
    b.a #error
    当我替换
     STORE_NAME 
    时与
     STORE_GLOBAL 
    它有效。但是我认为 STORE_NAME 用于在当前本地命名空间中存储一个值。但是顶级的本地命名空间是否与全局命名空间相同?例如
    locals() == globals() 
    如果仅使用,则在主作用域中为真。

    基本上:如果我使用内置编译函数编译“a = 3”,

    dis.dis() and bytecode's Code.from_code(codeobject) show STORE_NAME 
    .嗯

最佳答案

我已尝试重现您的步骤,一切正常。让我们逐步查看该过程。首先,代码创建。

这里我们导入所有我们需要的:

from byteplay import Code, LOAD_CONST, STORE_NAME, RETURN_VALUE

让我们创建一个带有适当参数的操作码列表(一个元组列表,每个元组包含操作码作为第一个元素,参数作为第二个元素):

lst = [
(LOAD_CONST, 3),
(STORE_NAME, 'a'),
(LOAD_CONST, None),
(RETURN_VALUE, None)
]

好了,到此为止。接下来,最负责的步骤是创建代码对象。它接收10 个参数。让我们看一下:

x = Code(
lst, # opcodes list (what we execute)
[], # outer scope variables (obviously, we don't have any here),
[], # arguments (nothing here),
False, # *args here? Nope
False, # **kwargs here? Nope
False, # !!!Important!!! DO WE CREATE NEW NAMESPACE? No! We use given!
'', # name ...
'', # filename ... who cares...
0, # first line number
'' # docstring
)

Attention! If the 6-th argument to code creation was set to True, you won't receive 'a' variable stored in locals after our code is executed. That's how functions work. They create their own namespace (co_names), and namespace we execute code in won't be patched with 'a' variable.

那么,让我们运行吧!

nsloc = {}   # locals to execute code with
nsglob = {} # globals to execute code with

# We could use one namespace for both but that doesn't matter

exec x.to_code() in nsglob, nsloc

print nsloc

而且,结果如预期的那样:

{'a': 3}

希望对您有所帮助。

关于python - STORE_NAME 和 STORE_GLOBAL 在主要范围内是等价的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8451691/

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