本文介绍了为什么exec()在函数内部调用时的工作原理有所不同,以及如何避免使用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to declare two functions within exec statement in python. Let's call them f1() and f2().

我发现,在某个函数内部调用 exec 时, f2()不可见 f1() .但是,将 exec 和函数调用放在全局代码中不会发生这种情况.

I've found out that when exec is invoked inside of some function, then f2() has no visibility of f1().However this doesn't happen when exec and function call are placed in global code.

# 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 在函数内部工作吗?

Can someone explain me how to avoid that NameError and make exec work inside of a function?

推荐答案

exec()接受globals的第二个参数.如文档中所述:

exec() accepts a second parameter for globals. As explained in the docs:

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

So you can make this work by explicitly passing in globals():

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

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

foo()

如果要精确控制范围,可以将对象传递到exec:

If you want to control the scope precisely, you can pass an object into exec:

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

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

foo() 

这篇关于为什么exec()在函数内部调用时的工作原理有所不同,以及如何避免使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 11:50