小编rba*_*ros的帖子

136
推荐指数
10
解决办法
8万
查看次数

exec() 方法中自定义命名空间的子类 python 字典

我正在尝试将字典子类化以用于 exec 方法。最终,我希望本地函数具有自定义名称范围行为。

在下面的代码中,函数b()实际上有正确的globals()字典可用,但是在解析z.

函数b()先不搜索locals()然后globals()呢?

非常令人费解。任何帮助表示赞赏。

t = '''
def b():
#   return (globals()['z']) #works
    return z #fails

b()
'''

class MyDict(dict):
    def __init__(self, g):
        dict.__init__(self)
        self.my_g = g


    def __getitem__(self, key):
        print("GET ", key)
        try:
            val = dict.__getitem__(self, key)
        except:
            print("GET exception1")
            val = self.my_g[key]
        return val


g = {'z':123}

md = MyDict(g)

#fails to find z
exec(t, md, md)

#works
#exec(t, g, g)
Run Code Online (Sandbox Code Playgroud)

输出

GET  b …
Run Code Online (Sandbox Code Playgroud)

python dictionary namespaces subclass exec

3
推荐指数
1
解决办法
898
查看次数

标签 统计

python ×2

dictionary ×1

exec ×1

namespaces ×1

subclass ×1