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

meInvent bbird jobmattcon at gmail.com
Tue Oct 25 22:59:37 EDT 2016


Hi Jerry,

how about custom function?

i change to node.op = ast.op2()


import ast 

def op2(a,b):
    return a*b+a

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.op2()
        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) 




On Thursday, October 20, 2016 at 12:34:55 AM UTC+8, Jerry Hill wrote:
> 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