Safe expression parser in Python
How can I allow users to execute mathematical expressions in a safe way? Do I need to write a full parser?
Is there something like ast.literal_eval(), but for expressions?
Solution 1:
The Pyparsing examples page lists several expression parsers:
http://pyparsing.wikispaces.com/file/view/fourFn.py - A conventional arithmetic infix notation parser/evaluator implementation using pyparsing (despite its name, this actually does 5-function arithmetic, plus several trig functions)
http://pyparsing.wikispaces.com/file/view/simpleBool.py - A boolean infix notation parser/evaluator, using a pyparsing helper method operatorPrecedence
, which simplifies the definition of infix operator notations
http://pyparsing.wikispaces.com/file/view/simpleArith.py http://pyparsing.wikispaces.com/file/view/eval_arith.py -
A pair of examples recasting fourFn.py using operatorPrecedence
. The first just parses and returns a parse tree, the second adds evaluation logic.
Solution 2:
What sort of expressions do you want? Variable assignment? Function evaluation?
SymPy
aims to become a full-fledged Python CAS.