在exec中分配的变量的NameError,虽然它存在于locals中?

时间:2016-11-16 17:10:25

标签: python python-3.x namespaces eval nameerror

当我运行下面的代码时,我得到/usr/local/brew/Cellar/jmeter/3.0/libexec/bin/jmeter

NameError

即使赋值似乎有效,我也可以通过手动索引到locals-namespace来返回它:

def foo():
    exec("data = [1, 2, 3]", globals(), locals())
    return data

foo()  # Returns an error:
# ---------------------------------------------------------------------------
# NameError                                 Traceback (most recent call last)
# <ipython-input-24-617677c4ff0e> in <module>()
#       3     return data
#       4
# ----> 5 foo()
# 
# <ipython-input-24-617677c4ff0e> in foo()
#       1 def foo():
#       2     exec("data = [1, 2, 3]")
# ----> 3     return data
#       4
#       5 foo()
# 
# NameError: name 'data' is not defined

怎么回事?

0 个答案:

没有答案