Python ast(抽象语法树):获取子节点的源字符串
我用
>>> 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?
(当然,我可以使用.walk或NodeVisitor并手动指定如何从节点构造字符串.但这并不能提供原始的源代码,因此必须注意括号等) >
(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.)
您不会获得 exact 原始源.但是 astor 包将为您提供与 recompile 相同的源代码.原始来源.
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.
编辑后添加 github上该版本提供的重构源明显优于最新版本提供的源(例如,括号更少和文档字符串处理得更好).我想即将发布一个新版本.
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.
(注释中提到的unparser包悲观地在所有内容上都加上了括号.)
(And the unparser package mentioned in the comments pessimistically puts parentheses on everything.)