读/重写/写python asts
astor的Python项目详细描述
PyPI: | https://pypi.org/project/astor/ |
---|---|
Documentation: | https://astor.readthedocs.io |
Source: | https://github.com/berkerpeksag/astor |
License: | 3-clause BSD |
Build status: |
astor的设计允许通过ast轻松操作python源代码。
还有一些类似的库,但astor主要关注以下方面:
- 往返返回python[1]:
- 修改后的ast不需要行号、ctx等 可直接编译,以便往返工作。
- 易于阅读生成的代码以及代码
- 可以往返两个不同的源树进行功能比较 差异,使用astor.rtrip工具(例如,在pep8编辑之后)。
- 转储ast
- 的漂亮打印
- 比往返代码更难阅读,但更准确地了解 正在进行中。
- 读取比从内置AST模块转储更容易
- 非递归treewalk
- 有时候你需要一个递归的treewalk(astor支持这个,从 在树的任何节点),但有时不需要这样做。阿斯特 不需要显式访问子节点,除非您希望:
- 您可以添加在访问节点的子节点之前执行的代码,和/或
- 您可以添加在访问节点的子节点后执行的代码,和/或
- 可以添加执行并阻止节点的子节点 已访问(也可以通过递归调用亲自访问)
- 编写基于对象名和/或属性名访问树的函数
- 轻松访问父节点进行树重写
[1] | The decompilation back to Python is based on code originally written by Armin Ronacher. Armin’s code was well-structured, but failed on some obscure corner cases of the Python language (and even more corner cases when the AST changed on different versions of Python), and its output arguably had cosmetic issues – for example, it produced parentheses even in some cases where they were not needed, to avoid having to reason about precedence. Other derivatives of Armin’s code are floating around, and typically have fixes for a few corner cases that happened to be noticed by the maintainers, but most of them have not been tested as thoroughly as astor. One exception may be the version of codegen maintained at github by CensoredUsername. This has been tested to work properly on Python 2.7 using astor’s test suite, and, as it is a single source file, it may be easier to drop into some applications that do not require astor’s other features or Python 3.x compatibility. |