语句eval'd似乎并未在具有相应全局变量和局部变量对象的环境中执行。eval全局变量和本地变量不能按预期工作
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也出现在全局变量中。它不是一个全局变量与当地人的问题 – Scott