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