Skip to content
Advertisement

“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})

The line for e2 (but not e1) generates an error:

NameError: name 'numpy' is not defined

Why?

Advertisement

Answer

I solved it by replacing:

f = "numpy.sin(x)"

with:

f = "__import__('numpy').sin(x)"
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement