Walking a py3k AST

The compiler module has been removed from py3k. Fortunately there's a replacement in the _ast module introduced in Python 2.5. Unfortunately, while the compiler module has a useful __repr__esentation for its AST objects...

>>> compiler.parse('x = 10')
    Module(None, Stmt([Assign([AssName('x', 'OP_ASSIGN')], Const(10))]))

This is not the case for the _ast module, so here's a function that will dump _ast.AST objects as a dict:

>>> import _ast
>>> from pprint import pprint
>>> def walk(node):
...     if isinstance(node, list):
...         return [walk(n) for n in node]
...     elif isinstance(node, _ast.AST):
...         return {node.__class__.__name__: dict(
...                 (field, walk(getattr(node, field))) for field in node._fields or []
...                 )}
...     else:
...         return node
... 
>>> st = compile('x = 10', '', 'exec', flags=_ast.PyCF_ONLY_AST)
>>> pprint(walk(st))
{'Module': {'body': [{'Assign': {'targets': [{'Name': {'ctx': {'Store': {}},
                                                       'id': 'x'}}],
                                 'value': {'Num': {'n': 10}}}}]}}