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

Jerry Hill malaclypse2 at gmail.com
Wed Oct 19 12:34:39 EDT 2016


On Wed, Oct 12, 2016 at 5:55 AM, meInvent bbird <jobmattcon at gmail.com> wrote:
> i just expect to
> rewrite + become multiply
> by edit the example in the link provided

This seems to work.  You need to define visit_BinOp instead of
visit_Num (since you want to mess with the binary operations, not the
numbers).  Then,in visit_BinOp, we just replace the ast.Add node with
an ast.Mult node.

import ast

class ChangeAddToMultiply(ast.NodeTransformer):
    """Wraps all integers in a call to Integer()"""
    def visit_BinOp(self, node):
        if isinstance(node.op, ast.Add):
            node.op = ast.Mult()
        return node

code = 'print(2+5)'
tree = ast.parse(code)
tree = ChangeAddToMultiply().visit(tree)
ast.fix_missing_locations(tree)
co = compile(tree, '<ast>', "exec")

exec(code)
exec(co)

-- 
Jerry



More information about the Python-list mailing list