"NameError: name 'numpy' is not defined" when calling eval()

"NameError: name 'numpy' is not defined" when calling eval()

x = 0
x2 = 0
f = "numpy.sin(x)"
e1 = eval(f)
e2 = eval(f, {"x":x2})

e2(但不是 e1)的行产生错误:

NameError: name 'numpy' is not defined

为什么?

我通过替换解决了它:

f = "numpy.sin(x)"

与:

f = "__import__('numpy').sin(x)"

由于在 e1 中,您没有覆盖全局变量,因此存在 numpy。在 e2 中,你是,所以解释器看不到你的导入。只需将 numpy 作为变量传入即可。

e2 = eval(f, {'numpy': numpy, 'x':x2})