Is there a math expressions parser + evaluator for Python?
I am not the first to ask this question, but answers usually point to eval()
. For instance,
I'd suggest using ast.parse and then whitelisting the parse tree.
tree = ast.parse(s, mode='eval')
valid = all(isinstance(node, whitelist) for node in ast.walk(tree))
if valid:
result = eval(compile(tree, filename='', mode='eval'),
{"__builtins__": None}, safe_dict)
Here whitelist
could be something like:
whitelist = (ast.Expression, ast.Call, ast.Name, ast.Load,
ast.BinOp, ast.UnaryOp, ast.operator, ast.unaryop, ast.cmpop,
ast.Num,
)