python - 为什么在函数内部调用时 exec() 的工作方式不同以及如何避免它

标签 python python-2.7 exec

我试图在 python 的 exec 语句中声明两个函数。我们称它们为 f1()f2()

我发现当 exec 在某个函数内部被调用时,f2() 没有 f1() 的可见性. 然而,当 exec 和函数调用放在全局代码中时,这不会发生。

# Case 1: Working fine

code = """
def f1(): print "bar"
def f2(): f1()
"""

exec(code)
f2() # Prints "bar" as expected
# Case 2: Throws NameError: global name 'f1' is not defined

code = """
def f1(): print "bar"
def f2(): f1()
"""

def foo():
    exec(code)
    f2() # NameError

foo()

有人可以向我解释如何避免 NameError 并使 exec 在函数内部工作吗?

最佳答案

exec() 接受 globals 的第二个参数。如 docs 中所述:

Note The built-in functions globals() and locals() return the current global and local dictionary, respectively, which may be useful to pass around for use as the second and third argument to exec().

因此,您可以通过显式传入 globals() 来完成这项工作:

code = """
def f1(): print ("bar")
def f2(): f1()
"""

def foo():
    exec(code, globals())
    f2() # works in python2.7 and python3

foo()

如果你想精确控制范围,你可以传递一个对象到exec:

code = """
def f1(): print ("bar")
def f2(): f1()
"""

def foo():
    context = {}
    exec(code, context)
    context['f2']() 

foo() 

关于python - 为什么在函数内部调用时 exec() 的工作方式不同以及如何避免它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55763182/

相关文章:

c - 调用 execlp() 时为 "Bad Address"

c - 为什么 ls 不能与 execvp 一起工作?

python - 如何用 `stdin=sys.stdin` 重现 `stdin=PIPE` ?

python - 对 DataFrame 中的 NaN 行应用 Map,Python 3.6

python - Pandas - 使用列中的特定模式提取字符串

Python:获取进程中更改的对象的实际值

python请求检查文件是否正确下载

linux - 为什么 "find -mmin -1 -exec du -cb {} + | grep total | head -1"和 "find -mmin -1 -exec du -ch {} + | grep total | head -1"不同

python - 无法从牧师模块中 pickle 贝叶斯对象

python - 银行账户类。如何让它更强大/更高效? (面向对象)