Search code examples
pythonexpressioninfix-notationarithmetic-expressions

Validate expression/infix in python


How do I validate an expression/infix in python? Is it possible? For example:

a-d*9
5-(a*0.3-d+(0.4-e))/k*5
(a-d*9)/(k-y-4.3*e)+(t-7*c)

Solution

  • If you want Python-style expressions, you can use the parser in the ast module and check for SyntaxError:

    >>> ast.parse('5-(a*0.3-d+(0.4-e))/k*5')
    <_ast.Module object at 0x7fc7bdd9e790>
    >>> ast.parse('5-(a*0.3-d+(0.4-e))/k*')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/usr/lib/python2.6/ast.py", line 37, in parse
        return compile(expr, filename, mode, PyCF_ONLY_AST)
      File "<unknown>", line 1
        5-(a*0.3-d+(0.4-e))/k*
                            ^
    SyntaxError: unexpected EOF while parsing
    

    Though that might parse much more than you actually need:

    >>> ast.parse('def spam(): return "ham"')
    <_ast.Module object at 0x7fc7bdd9e790>
    

    so you might want to inspect the returned parse tree carefully.