How to evaluate user input mathematical expressions such as power safely?
Tried using ast.literal_eval
but it raises an exception.
>>> import ast
>>> ast.literal_eval('2**2')
ValueError: malformed node or string: <_ast.BinOp object at ...>
How to evaluate user input mathematical expressions such as power safely?
Tried using ast.literal_eval
but it raises an exception.
>>> import ast
>>> ast.literal_eval('2**2')
ValueError: malformed node or string: <_ast.BinOp object at ...>
ast.literal_eval
(although it actually supports addition and substraction) is intended for evaluating literals only. To safely evaluate mathematical expressions, you should construct the AST yourself using ast.parse(some_expression, mode="eval")
and check if it only contains literals and mathematical operations using ast.walk()
. To evaluate an AST use something like eval(compile(the_ast, "<string>", "eval"))
.
See this website for more information about ASTs: https://greentreesnakes.readthedocs.io/
You can use seval
package for arithmetic operations and literals safe evaluation.
>>> import seval
>>> seval.safe_import('2 ** 2')
4