相关疑难解决方法(0)

Why exec() works differently when invoked inside of function and how to avoid it

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

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
Run Code Online (Sandbox Code Playgroud)
# Case 2: Throws NameError: …
Run Code Online (Sandbox Code Playgroud)

python exec python-2.7

4
推荐指数
1
解决办法
67
查看次数

标签 统计

exec ×1

python ×1

python-2.7 ×1