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

  • submit to reddit
        Simplest AST visitor. More on this blog post :
<a href=""></a>

import compiler
class CodePrinter:
    def __init__(self):
        self.src = ''
    def visitName(self,t):
        self.src +=
    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 += + " = "
def pretty_print(node):
    myvisitor = CodePrinter()
    # compiler.walk return the visitor instance : 2nd arg
    return compiler.walk(node, myvisitor).src