Safe way to parse user-supplied mathematical formula in Python
<p>Is there a math expressions parser + evaluator for Python? </p>

<p>I am not the first to ask this question, but answers usually point to <code>eval()</code>. For instance, one could do this:</p>

<pre><code>&gt;&gt;&gt; safe_list = ['math','acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'abs']
&gt;&gt;&gt; safe_dict = dict([ (k, locals().get(k, None)) for k in safe_list ])
&gt;&gt;&gt; s = "2+3"
&gt;&gt;&gt; eval(s, {"__builtins__":None}, safe_dict)
5
</code></pre>

<p>But this is <a href="http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html">not safe</a>:</p>

<pre><code>&gt;&gt;&gt; s_badbaduser = """
... (lambda fc=(
...     lambda n: [
...         c for c in 
...             ().__class__.__bases__[0].__subclasses__() 
...             if c.__name__ == n
...         ][0]
...     ):
...     fc("function")(
...         fc("code")(
...             0,0,0,0,"KABOOM",(),(),(),"","",0,""
...         ),{}
...     )()
... )()
... """
&gt;&gt;&gt; eval(s_badbaduser, {"__builtins__":None}, safe_dict)
Segmentation fault
</code></pre>

<p>Also, using <code>eval</code> for parsing and evaluating mathematical expressions just seems wrong to me. </p>

<p>I have found <a href="http://www.bestcode.com/html/evaluate_math_expressions_pyth.html">PyMathParser</a>, but it also uses <code>eval</code> under the hood and is no better:</p>

<pre><code>&gt;&gt;&gt; import MathParser
&gt;&gt;&gt; m=MathParser.PyMathParser()
&gt;&gt;&gt; m.expression = s_badbaduser
&gt;&gt;&gt; m.evaluate();
Segmentation fault
</code></pre>

<p>Is there a library available that would parse and evaluate mathematical expression without using Python parser?</p>
