0

I am trying to develop an equation parser in python with eventually sub formulas. The idea is that a user might give an equation whose variables are not all known. But some sub-formulas might be defined for these undefined variables. The program should then replace the unknown variable by the sub formula. Using the help provided by @ebarr here, I have further developed the idea but I fail due to a stupid issue: when replace a variable by a sub-formula, ast.parse always deletes the right and left parenthesis which gives a bad final formula. Any idea on how to preserve the parenthesis ? Thanks !

import ast

list_know_var = ['vx', 'vy', 'vz', 'c']
equation = 'M = V  * V / c'
know_equations = {'V': 'vx + 1.'}

# initial equation
parsed_equation = ast.parse(equation)

# the class that automatically dives into the nodes of the AST
# to check for all variables definition
class AdaptEquation(ast.NodeTransformer):

    def visit_Name(self, node):
        # checking that the variable is know
        if node.id not in list_know_var:
            if node.id in know_equations.keys():
                node = ast.parse(know_equations[node.id]).body[0].value
        return node

# adapted equation
AdaptEquation().visit(parsed_equation)

# and its human readable expression
import codegen
print 'expected equation: M = (vx + 1) * (vx + 1) / c'
>>> expected equation: M = (vx + 1) * (vx + 1) / c
print 'adapted equation: ', codegen.to_source(parsed_equation)
>>> adapted equation:  M = vx + 1.0 * vx + 1.0 / c
Community
  • 1
  • 1
AdrienG
  • 180
  • 8

1 Answers1

1

I found a solution. Use Astor instead of Codegen. Even though I appreciate Codegen, I must say its buggy. Astor was built on top of Codegen, is newer and has more features. Here's an example of what you want using Astor:

import astor
import ast
test_code = "x=1-(x+y)"
abstract_syntax_tree = ast.parse(test_code)
print astor.to_source(abstract_syntax_tree)
print 'done'

#output
#x = (1 - (x + y))
#done
sudouser2010
  • 171
  • 1
  • 6