0

I have a string expression like "((12)*2+(12)+0)".

The question is I want to calculate this expression. I can use eval() function. Is there any other way? I also checked ast=compiler.parse(eq) and it return Module(None, Stmt([Discard(Add((Add((Mul((Const(12), Const(2))), Const(12))), Const(0))))])) something like that.

How to parse abstract syntax tree?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Munkhtsogt
  • 171
  • 1
  • 2
  • 11
  • You might be able to use [`ast.parse()`](http://docs.python.org/2/library/ast.html#ast.parse) to get the Python AST for a chunk of code. – millimoose Feb 22 '13 at 09:58
  • Thank you for reply. Coudl you give me little explanation? – Munkhtsogt Feb 22 '13 at 10:02
  • Also, [SymPy](http://sympy.org/en/index.html) should be able to evaluate maths expressions and then some. – millimoose Feb 22 '13 at 10:02
  • Not really since I've never used the module, I'm just aware of its existence. – millimoose Feb 22 '13 at 10:03
  • Please see this post: [Equation parsing in Python](http://stackoverflow.com/questions/594266/equation-parsing-in-python). – longhua Feb 22 '13 at 10:03
  • 1
    That's not an equation, it's an expression. – Bakuriu Feb 22 '13 at 10:04
  • There is no simple way. You probably want to check for the [`NodeVisitor`](http://docs.python.org/2/library/ast.html#ast-helpers) class. Using this you could check if the resulting syntax-tree contains only safe operations, and in this case you could be sure if it is safe to `eval` the expression, or you could eval it by hand while walking the tree. – Bakuriu Feb 22 '13 at 10:17

0 Answers0