STORE_UName和STORE_UGlobal是否在主作用域中等效?

2024-06-16 21:42:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我想我对Python中的模块名称空间有点困惑。 我和比泰普拉一起玩,这就是我尝试过的:

  1. 我构建了一个操作码列表,相当于:(byteplay的printcodelist)—>

    
    0 LOAD_CONST           3
    1 STORE_NAME           a
    2 LOAD_CONST           None
    3 RETURN_VALUE  
    

    但是当我这样做的时候:

    ^{pr2}$

    当我

    ^{pr3}时也会发生同样的情况$ 当我用
     STORE_GLOBAL 
    it替换^{pr4}$时很管用。不过我认为STORE_NAME用于在当前本地存储值命名空间。但是顶层的本地命名空间和全局命名空间不一样吗? 例如
    locals() == globals() 
    如果只使用它,则在主作用域中为真。

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

    ^{pr7}$。 嗯

Tags: 模块storenamegt名称none列表return
1条回答
网友
1楼 · 发布于 2024-06-16 21:42:40

我试着重现你的舞步,一切都很好。让我们一步一步地看这个过程。首先,代码创建。在

在这里,我们导入我们需要的一切:

from byteplay import Code, LOAD_CONST, STORE_NAME, RETURN_VALUE

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

^{pr2}$

好吧,说完了。接下来,最负责任的步骤是创建代码对象。它接收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}

希望能帮上忙。在

相关问题 更多 >