繁体   English   中英

Python ast:确定 FunctionDef 是否在 ClassDef 内

[英]Python ast: decide whether a FunctionDef is inside a ClassDef or not

我想从 Python 源代码构建一个 ast,然后从 ast 中获取特定信息。 我面临以下问题:虽然遍历 ClassDef 的主体是可行的,但我如何确定方法是否在类内部。

我构建的代码来自:

class A:
    def foo(self):
        pass


def foo(self):
    pass

在这个例子中,我将命中所有foo但我无法判断它是否来自类(因为它们具有相同的参数集,命名错误,但代码可以解释)。

    def build_ast(self):
        with open(self.path, 'r', encoding='utf-8') as fp:
            tree = ast.parse(fp.read())
            for node in ast.walk(tree):
                if isinstance(node, ast.FunctionDef):
                    print(ast.dump(node))
                    # access the parent if it has

我对我的最终解决方案并不完全满意,但显然它适用于 Python 3.8.3:

根据我的经验, ast.walk在 FunctionsDef 节点之前遍历 ClassDef 节点。

def build_ast(self):
    with open(self.path, 'r', encoding='utf-8') as fp:
        tree = ast.parse(fp.read())

        for node in ast.walk(tree):
            if isinstance(node, ast.FunctionDef):
                if hasattr(node, "parent"):
                    print(node.parent.name, node.name)
                else:
                    print(node.name, "is not in a class.")
            if isinstance(node, ast.ClassDef):
                for child in node.body:
                    if isinstance(child, ast.FunctionDef):
                        child.parent = node

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM