語句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