[Python-ideas] AST Pretty Printer
Ryan Gonzalez
rymg19 at gmail.com
Sat Sep 14 02:25:25 CEST 2013
Note: I didn't know who to reply to, so I just restarted the thread with
the same subject.
Here is the code:
class astpp(ast.NodeVisitor):
def __init__(self, tree):
super(ast.NodeVisitor, self).__init__()
self.indent = 0
self.visit(tree)
def _print(self, text):
print (' ' * self.indent + text)
def generic_visit(self, node):
self._print(node.__class__.__name__ + '(')
self.indent += 1
for name, item in node.__dict__.iteritems():
if isinstance(item, ast.AST):
self._print(name + '=')
self.indent += 1
self.generic_visit(item)
self.indent -= 1
elif isinstance(item, list):
self._print(name + '=[')
self.indent += 1
[self.generic_visit(attr) for attr in item]
self.indent -= 1
self._print(']')
else:
self._print(name + '=' + str(item))
self.indent -= 1
self._print(')')
Sample usage:
astpp('''len('My friends are my power!')''')
Output:
Module(
body=[
Expr(
lineno=1
value=
Call(
col_offset=0
starargs=None
args=[
Str(
s=My friends are my power!
lineno=1
col_offset=4
)
]
lineno=1
func=
Name(
ctx=
Load(
)
id=len
col_offset=0
lineno=1
)
kwargs=None
keywords=[
]
)
col_offset=0
)
]
)
--
Ryan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130913/59b969ad/attachment.html>
More information about the Python-ideas
mailing list