4

I use

>>> import ast
>>> T = ast.parse('a * (b + c)', mode='eval').body

to get an abstract syntax tree of some (mathematically looking; but this shouldn't matter) expression.

Now I want to get back the source string of some particular node. For example

>>> get_source_back(T.right)
'(b + c)'

Is there a solution for this somewhere?

(Of course I could use .walk or NodeVisitor and manually specify how to construct a string out of a node. But this does not give me the original source and I have to be careful with parentheses and so on.)

Daniel Krenn
  • 251
  • 2
  • 9
  • getting the source back is not a simple task, this modified version of unparse.py https://github.com/python/cpython/blob/master/Tools/parser/unparse.py would get the source back if using exec,http://pastebin.com/BUeGLdid – Padraic Cunningham Aug 21 '15 at 18:28
  • Possible duplicate of [Given an AST, is there a working library for getting the source?](https://stackoverflow.com/questions/3774162/given-an-ast-is-there-a-working-library-for-getting-the-source) – Ben Jones Jul 16 '18 at 17:57

1 Answers1

2

You won't get the exact original source back. But the astor package will give you back source that will recompile identically to the original source.

Edited to add The reconstituted source provided by the version on github is substantially better than the source provided by the most recent release (e.g. fewer parentheses and better handling of docstrings). A new release is imminent, I think.

(And the unparser package mentioned in the comments pessimistically puts parentheses on everything.)

Patrick Maupin
  • 8,024
  • 2
  • 23
  • 42