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?
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
operatorPrecedence
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.
2.1m questions
2.1m answers
60 comments
57.0k users