Equation parsing in Python

 f = parser.parse('sin(x)*x^2').to_pyfunc()

Where parser could be defined using PLY, pyparsing, builtin tokenizer, parser, ast.

Don't use eval on user input.


Python's own internal compiler can parse this, if you use Python notation.

If your change the notation slightly, you'll be happier.

import compiler
eq= "sin(x)*x**2"
ast= compiler.parse( eq )

You get an abstract syntax tree that you can work with.


You can use Python parser:

import parser
from math import sin

formula = "sin(x)*x**2"
code = parser.expr(formula).compile()
x = 10
print(eval(code))

It performs better than pure eval and, of course, avoids code injection!