views:

86

answers:

2

Is there a way to convert a given Python abstract syntax tree (AST) to a source code?

Here is a good example of how to use Python's ast module, specifically a NodeTransformer. I was looking for a way to convert the resulting AST back to source, so the changes can be inspected visually.

A: 

Our DMS Software Reengineering Toolkit with its Python Front End can parse Python and generate full Python ASTs, carry out custom analyses and transformations on such ASTs (or assemble them from arbitrary fragments), and regenerate compilable Python source text complete with comments.

Ira Baxter
+2  A: 

The Python source tree contains an implementation of this: unparse.py in the Demo/parser directory: http://svn.python.org/projects/python/trunk/Demo/parser/unparse.py

Ned Batchelder
Thanks. It looks somewhat buggy, but I can use it as a starting point.
Muhammad Alkarouri
Interesting, I didn't look closely, what sorts of bugs do you see?
Ned Batchelder
Scratch that. Looks like it is alright in Python 2.7. I was trying on 2.6 and I found problems with things like `for ... else`, but 2.7 is fine so far.
Muhammad Alkarouri