Skip to content
Advertisement

math module not working in a string for eval

Suppose I have this code:

import math
import traceback


def getValue(s,p,val):
    d={}
    for k in range(len(p)):
        d[p[k]]=val[k]

    y = eval(s,d)
    return str(round(y,3))

values = [5,3]
parameters = ['var1','var2']
s = 'var2*3/2 + math.log(100)-var1**2'
x = getValue(s,parameters,values)
 print x

but I only get this error: NameError: name ‘math’ is not defined

How can I fix this?

Advertisement

Answer

The second parameter to eval, if present, should reference the global namespace. Here, you explicitely assigned an empty dict to it, so you don’t have any access to the name math of the global namespace. You could assign d to the local namespace of eval instead:

import math
import traceback


def getValue(s,p,val):
    d = {}
    for k in range(len(p)):
        d[p[k]]=val[k]

    y = eval(s, globals(), d)
    return str(round(y,3))

values = [5,3]
parameters = ['var1','var2']
s = 'var2*3/2 + math.log(100)-var1**2'
x = getValue(s,parameters,values)
print(x)
# -15.895
Advertisement