Python ast(抽象语法树):获取子节点的源字符串 [英] Python ast (Abstract Syntax Trees): get back source string of subnode

查看:388
本文介绍了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.)

这篇关于Python ast(抽象语法树):获取子节点的源字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆