Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SymPy: Safely parsing strings

Tags:

python

sympy

SymPy comes equipped with the nice sympify() function which can parse arbitrary strings into SymPy expressions. But it has two major drawbacks:

  1. It is not safe, as it relies on the notorious eval()
  2. It automatically simplifies the read expression. e.g. sympify('binomial(5,3)') will return the expression 10.

So my questions are:

First, is there a way to "just parse" the string, without any additional computations? I want to achieve something like this effect:

latex(parse('binomial(5,3)')) #returns '{\\binom{5}{3}}'

Second, is there an accepted way to sympify (i.e. parse and compute) arbitrary user-generated strings while remaining safe? It is done by SymPy Gamma, so it's possible in practice, but the question is how much dirty work is needed.

like image 637
Gadi A Avatar asked Nov 10 '22 14:11

Gadi A


1 Answers

Look at the internal functions in the SymPy parsing module.

There is no official way to do it. We need to rewrite sympify to avoid eval. Note that SymPy gamma just uses sympify. It remains safe because it's sandboxed on the App Engine.

like image 73
asmeurer Avatar answered Nov 15 '22 07:11

asmeurer