how to evaluate a ast tree and change Add to Multiply ?

meInvent bbird jobmattcon at gmail.com
Wed Oct 12 05:32:58 EDT 2016


import sys
import parser
import ast
from collections import deque


class ChangeAddtoMultiply(ast.NodeTransformer):
    """Wraps all integers in a call to Integer()"""
    def visit_Num(self, node):
        if isinstance(node.n, int):
            return ast.Call(func=ast.Name(id='Add', ctx=ast.Load()),
                            args=[node], keywords=[])
        return node


tree = ast.parse('2+5')
for node in ast.walk(tree):
    print(str(node))

eval(tree)




More information about the Python-list mailing list