Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe expression parser in Python

Tags:

python

parsing

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?

like image 273
Ivo Danihelka Avatar asked Aug 27 '10 08:08

Ivo Danihelka


People also ask

What parser does Python use?

Making experiments. As the generated C parser is the one used by Python, this means that if something goes wrong when adding some new rules to the grammar you cannot correctly compile and execute Python anymore.

How does Python parser work?

Python parsing is done using various ways such as the use of parser module, parsing using regular expressions, parsing using some string methods such as split() and strip(), parsing using pandas such as reading CSV file to text by using read. csv, etc.


1 Answers

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.

like image 175
PaulMcG Avatar answered Oct 13 '22 15:10

PaulMcG