3

I am using the 'ast' module in python to create a Abstract Syntax Tree. I want to be able to edit the AST(I am editing with 'ast.NodeTransformer') and then take that new tree and write it to a new python file. According to the website "http://greentreesnakes.readthedocs.org/en/latest/index.html" there is no way to do this without using a third party package. Is this true, or can I write a AST to a new python file using the 'ast' module? If so, how do I do it? It seems like 'ast' would support this.

user2672165
  • 2,986
  • 19
  • 27
baallezx
  • 471
  • 3
  • 14

1 Answers1

2

You will need a third party module called codegen.py, but it itself just uses the bulitin AST machinery under the hood its very simple. From there you can use the builtin ast.NodeTransformer machinery to transform the AST nodes.

import ast
import codegen

class Visitor(ast.NodeTransformer):

    def visit_Num(self, node):
        return ast.Num(42)

x = Visitor()
t = ast.parse('x + y + z + 3')
out = x.visit(t)
print codegen.to_source(out)
# x + y + z + 42
Stephen Diehl
  • 8,271
  • 5
  • 38
  • 56