【发布时间】:2012-08-29 19:25:26
【问题描述】:
我正在尝试对字典进行子类化以在 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)
输出
GET b
Traceback (most recent call last):
File "/project1/text12", line 31, in <module>
File "<string>", line 6, in <module>
File "<string>", line 4, in b
NameError: global name 'z' is not defined
【问题讨论】:
-
返回 z 失败,因为没有变量 z。你说 return (globals()['z']) 有效,你想在返回 z 的时候完成什么?
-
我希望 z 从传入的全局字典中解析为在下面的答案中工作。干杯
标签: python dictionary namespaces exec subclass