ASPN ActiveState Programmer Network  
ActiveState, a division of Sophos
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups
Submit Recipe
My Recipes

All Recipes
All Cookbooks


View by Category

Title: AST Pretty Printer
Submitter: Martin Blais (other recipes)
Last Updated: 2007/10/09
Version no: 1.0
Category: Debugging

 

Not Rated yet


Description:

A function that outputs a human-readable version of a Python AST.

Source: Text Source

"""Python AST pretty-printer.

To me, it is totally unf*ckinbelievable that the standard Python compiler module
does not come with a pretty-printer for the AST. Here is one.
"""

import sys
from compiler.ast import Node


def pprintAst(ast, indent='  ', stream=sys.stdout):
    "Pretty-print an AST to the given output stream."
    rec_node(ast, 0, indent, stream.write)

def rec_node(node, level, indent, write):
    "Recurse through a node, pretty-printing it."
    pfx = indent * level
    if isinstance(node, Node):
        write(pfx)
        write(node.__class__.__name__)
        write('(')

        if any(isinstance(child, Node) for child in node.getChildren()):
            for i, child in enumerate(node.getChildren()):
                if i != 0:
                    write(',')
                write('\n')
                rec_node(child, level+1, indent, write)
            write('\n')
            write(pfx)
        else:
            # None of the children as nodes, simply join their repr on a single
            # line.
            write(', '.join(repr(child) for child in node.getChildren()))

        write(')')

    else:
        write(pfx)
        write(repr(node))


if __name__ == '__main__':
    def test():
        import compiler
        pprintAst(compiler.parseFile(__file__))
    test()

Discussion:

To me, it is totally unbelievable that the standard Python
compiler module does not come with a pretty-printer for the AST. It
just blows my mind, completely. I don't know how many times I have
been hacking around one until today.

You can find the latest version of this code in the Snakefood project source.
This really should belong in the standard compiler module (and that code should be improved too, the visitors are always a PIA to use).



Add comment

Number of comments: 1

had to define an any() function for this to work with python 2.4.3, Ian Barnard, 2007/11/28
like this:

def any(l):
	for item in l:
		if item:
			return True
	return False

Add comment



Highest rated recipes:

1. A simple XML-RPC server

2. Web service accessible ...

3. IPy Notify

4. Changing return value ...

5. Quantum Superposition

6. Pickle objects under ...

7. Generalized delegates ...

8. Reorder a sequence (uses ...

9. Setting Win32 System ...

10. ObjectMerger




Privacy Policy | Email Opt-out | Feedback | Syndication
© 2006 ActiveState Software Inc. All rights reserved.