跳转到主要内容

基于AST的片段化源代码重构工具包

项目描述

重构

PyPI version Documentation Try It

简单、无烦恼、无依赖、基于AST的片段化源代码重构和转换工具包。

为什么?

我们的框架主要基于“简单但有效”的转换原则。我们专注于针对源代码小段落的重构,并由此展开。这使得我们能够直接对分析和转换的单个格式进行操作。这是我们与其他类似工具相比的优势所在。

如何?

我们不多谈细节,但为了给您一个预览,我们可以尝试编写一个规则,将标识符placeholder替换为42

import ast
from refactor import Rule, Replace, run

# Each refactor transformer inherits from "refactor.Rule"
class FillPlaceholders(Rule):

    # And each rule implements a "match()" method, which would
    # receive every node in the tree in a breadth-first order.
    def match(self, node: ast.AST) -> Replace:
        # This is where things get interesting. Instead of just writing
        # filters with if statements, you can use the following assert
        # based approach (a contract of transformation).

        # For this case, our contract is going to be: if the given node
        # is an identifier with the name of "placeholder", it will be
        # replaced with literal "42".
        assert isinstance(node, ast.Name)
        assert node.id == "placeholder"

        # And this is where we choose what action we are taking for the
        # given node (which we have verified with our contract). There
        # are multiple transformation actions, but in this case what we
        # need is something that replaces a node with another one.
        replacement = ast.Constant(42)
        return Replace(node, replacement)

if __name__ == "__main__":
    # And finally in here, we just use the default CLI that comes
    # bundled with refactor. When provided with a bunch of rules,
    # it creates a simple interface that can process given files
    # show the diff for changes and even apply them.
    run(rules=[FillPlaceholders])

如果我们在一个文件上运行上述规则,我们可以看到它的表现

--- test_file.py
+++ test_file.py

@@ -1,11 +1,11 @@

def main():
-    print(placeholder * 3 + 2)
+    print(42 * 3 + 2)
-    print(2 +               placeholder      + 3)
+    print(2 +               42      + 3)
     # some comments
-    placeholder # maybe other comments
+    42 # maybe other comments
     if something:
         other_thing
-    print(placeholder)
+    print(42)

if __name__ == "__main__":
     main()

想了解更多,请查看我们的 文档

项目详情


下载文件

下载适用于您平台的文件。如果您不确定该选择哪个,请了解有关安装包的更多信息。

源代码分发

refactor-0.6.3.tar.gz (25.0 kB 查看哈希值)

上传时间 源代码

构建分发

refactor-0.6.3-py3-none-any.whl (29.4 kB 查看哈希值)

上传时间 Python 3

由以下支持