当在 exec
中定义变量/函数时,它似乎转到 locals()
而不是 globals()
如何我可以改变这种行为吗?只有当您将全局和本地字典传递给 exec
时才会发生这种情况。
例子:
exec("""
a = 2
def foo():
print a
foo()""") in {},{}
当你尝试这样做时:
NameError: global name 'a' is not defined
最佳答案
乍一看我也觉得奇怪。但是有了更多的输出,我找到了原因:
>>> g, l = {}, {}
>>> print id(g), id(l)
12311984 12310688
>>>
>>> exec '''
... a = 2
... print 'a' in globals(), 'a' in locals(), id(globals()), id(locals())
... def f():
... print 'a' in globals(), 'a' in locals(), id(globals()), id(locals())
... f()
... ''' in g, l
False True 12311984 12310688
False False 12311984 12311264
如 http://effbot.org/pyfaq/what-are-the-rules-for-local-and-global-variables-in-python.htm 中所述:
In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be a local. If a variable is ever assigned a new value inside the function, the variable is implicitly local, and you need to explicitly declare it as global.
因此,一种解决方案是对全局变量和局部变量使用相同的字典:
>>> l = {}
>>> exec '''
... a = 2
... def f():
... print a
... f()
... ''' in l, l
2
关于python - Python exec 中的作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11326137/