Visit Python Abstract Syntax Tree
Join the DZone community and get the full member experience.
Join For FreeSimplest AST visitor. More on this blog post :
http://www.biais.org/blog/index.php/2007/01/10/9-visit-python-abstract-syntax-tree
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
Abstract syntax
Python (language)
Tree (data structure)
Syntax (programming languages)
Opinions expressed by DZone contributors are their own.
Comments