Search code examples
pythonfunctionmoduleeval

Error passing to eval() an expression with a function from an imported module


I'm relatively new to Python, but I'm bewildered with this issue. Could anyone help me?

I have defined a function for plotting a math-function whose expression is passed as a string:

def plot_function(str_function,a,b):
    import matplotlib.pyplot as plt
    import numpy as np
    
    f = lambda x: eval(str_function)
    x=np.linspace(a,b,200)  
    y=f(x)
    plt.plot(x,y)
    plt.show()

It works fine calling it by:

plot_function('2*x',-10,10)

But it yields the error name "np" is not defined calling it by:

plot_function('np.sin(x)',-10,10)

Could anyone explain the reason? Thanks.


Solution

  • eval built-in function give two parameter like this

    eval(expression, [globals[, locals]])
    

    If the second parameter does not exist the default value set to global and you define numpy import as np in the local function then np does not exist in the global