Created
February 1, 2015 14:11
-
-
Save polyvertex/d121c1bf71ac1437411e to your computer and use it in GitHub Desktop.
Python AST Pretty Printer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ast | |
def dbg_astdump(node, annotate_fields=True, include_attributes=False, indent=' '): | |
""" | |
AST Pretty Printer | |
Code copied and slightly modified from: | |
http://alexleone.blogspot.com/2010/01/python-ast-pretty-printer.html | |
""" | |
def _format(node, level=0): | |
if isinstance(node, ast.AST): | |
fields = [(a, _format(b, level)) for a, b in ast.iter_fields(node)] | |
if include_attributes and node._attributes: | |
fields.extend([(a, _format(getattr(node, a), level)) | |
for a in node._attributes]) | |
return ''.join([ | |
node.__class__.__name__, | |
'(', | |
', '.join(('%s=%s' % field for field in fields) | |
if annotate_fields | |
else (b for a, b in fields)), | |
')']) | |
elif isinstance(node, list): | |
lines = ['['] | |
lines.extend((indent * (level + 2) + _format(x, level + 2) + ',' | |
for x in node)) | |
if len(lines) > 1: | |
lines.append(indent * (level + 1) + ']') | |
else: | |
lines[-1] += ']' | |
return '\n'.join(lines) | |
return repr(node) | |
if not isinstance(node, ast.AST): | |
raise TypeError('Expected AST, got %r' % node.__class__.__name__) | |
return _format(node) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment