Python exec中的范围

当在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.

所以一个解决方案是对全局变量和本地变量使用相同的dict:

>>> l = {}
>>> exec '''
... a = 2
... def f():
...     print a
... f()
... ''' in l, l
2
上一篇:这个__import__功能是否正确?


下一篇:Postman提取返回值