Over a million developers have joined DZone.

Visit Python Abstract Syntax Tree

DZone's Guide to

Visit Python Abstract Syntax Tree

Free Resource
Simplest AST visitor. More on this blog post :

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

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}