python - Python exec 中的作用域

标签 python scope exec global locals

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

相关文章:

c - 我如何知道对特定程序使用哪个 exec 命令?

linux - exec 函数系列内部如何工作?

python - cython中的嵌套循环优化: is there a faster way to setup this code example?

python - BeautifulSoup : extract weather info : table --> Excel file

c++ - 声明与 const 变量和成员函数相同的标识符

javascript - 如何在 js 中创建一个非 block 范围的常量?

ruby - 由 Rufus Scheduler 触发的 Sinatra 事件

python - 如何使用 Conda 下载 python 包,然后离线安装?

python - GAE 中应该使用什么来存储数据?

php - 如何在没有 exec() 函数的情况下从 mysql 导出数据库