小编Tob*_*asM的帖子

Python NodeTransformer:如何删除节点?

我正在尝试 AST 操作。目前我正在尝试从输入 AST 中删除某些节点。我认为 NodeTransformer 类是实现此目的的合适工具。遗憾的是,它的表现并不如预期。

文档说

“NodeTransformer 将遍历 AST,并使用访问者方法的返回值来替换或删除旧节点。如果访问者方法的返回值为 None,则该节点将从其位置中删除,否则将替换为返回值。”

现在看看我的程序:

import _ast
import ast
import sys

#ast transformer
class MyTransformer(ast.NodeTransformer):

    def iterate_children(self, node):
        """
        helper
        """
        children = ast.iter_child_nodes(node)
        for c in children:
            self.visit(c)

    def generic_visit(self, node):
        """
        default behaviour
        """
        print("visiting: "+node.__class__.__name__)
        self.iterate_children(node)
        return node

    def visit_For(self, node):
        """
        For nodes: replace with nothing
        """
        print("removing a For node")
        return None



#read source program
filename = sys.argv[1]
with open (filename, "r") as myfile:
    source = …
Run Code Online (Sandbox Code Playgroud)

python abstract-syntax-tree python-3.2

5
推荐指数
1
解决办法
4078
查看次数

标签 统计

abstract-syntax-tree ×1

python ×1

python-3.2 ×1