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.)

2

1 Answer 1

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.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.