I am working on Python code to replace an expression containing ‘/’ with actual function call. For eg: ‘(n/7-7) +(n/3+3)’ should become ‘(div(n,7)-7 + ( div(n,3)+3)’. Please note only ‘/’ operand needs to be replaced.
I am using ast.NodeVisitor for the same.
class visitor(ast.NodeVisitor):
def visit_BinOp(self, node):
if isinstance(node.op,ast.Div):
return f'{self.visit(node.op)}({self.visit(node.left)},{self.visit(node.right)})'
else:
return self.generic_visit(node)
def tokenize(source):
return visitor().visit(ast.parse(source, mode='eval'))
I am calling this function as:
expression = 'n/5-1'
expression = tokenize(expression)
But expression value returned is None. Is there something wrong in the above code? I also tried to overload visit_Div instead of visit_BinOp but at that level left and right has to be accessible because of which I figured maybe overloading visit_BinOp is better.