【发布时间】:2017-04-11 14:49:27
【问题描述】:
语句 eval'd 似乎实际上并未在具有相应全局对象和局部对象的环境中执行。
def f(x):
return g(x)*3
def g(x):
return x**2
funcs = {"f":f,"g":g}
del globals()['g'] # to keep them out of the global environment
del globals()['f']
eval("f(2)",globals(),funcs)
错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
File "<stdin>", line 2, in f
NameError: name 'g' is not defined
更新:
更多说明:
>>> exec("print(globals()['g'])",{**globals(),**funcs})
<function g at 0x7feb627aaf28>
>>> eval("f(2)",{**globals(),**funcs})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
File "<stdin>", line 2, in f
NameError: name 'g' is not defined
编辑
这不是this question 的副本。即使作为全局函数传递,函数 g 也无法查找。
【问题讨论】:
-
这不是那个问题的重复,因为 NameError 也发生在全局变量中。这不是全局与本地的问题
标签: python python-3.5