DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Visit Python Abstract Syntax Tree

01.24.2007
| 6127 views |
  • submit to reddit
        Simplest AST visitor. More on this blog post :
<a href="http://www.biais.org/blog/index.php/2007/01/10/9-visit-python-abstract-syntax-tree">http://www.biais.org/blog/index.php/2007/01/10/9-visit-python-abstract-syntax-tree</a>

import compiler
 
class CodePrinter:
    def __init__(self):
        self.src = ''
 
    def visitName(self,t):
        self.src += t.name
 
    def visitConst(self,t):
        self.src += str(t.value)
 
    def visitStmt(self, t):
        for i in t:
            a = pretty_print(i)
            self.src += a + "\n"
 
    def visitAssName(self, t):
        self.src += t.name + " = "
 
def pretty_print(node):
    myvisitor = CodePrinter()
    # compiler.walk return the visitor instance : 2nd arg
    return compiler.walk(node, myvisitor).src