RuntimeError: maximum recursion depth exceeded while calling a Python object with ast

RuntimeError: maximum recursion depth exceeded while calling a Python object with ast

我正在使用 ast to get information from Python source files (as per the suggestion )。为此,我扩展了 ast.NodeVisitor 并且它在大多数源文件中运行良好。但是,我收到

RuntimeError: maximum recursion depth exceeded while calling a Python object

当我在大型 classes 上使用它时出现异常(~2000 行。糟糕的做法。我知道 :))。当我在崩溃时检查堆栈时,我发现确实有一个非常深的递归正在进行,但它似乎并没有在循环中进行。也就是说,如果递归继续进行一些,它将成功完成。有办法解决这个问题吗?

我不确定这是否与此有关,但是这个大 class 包含一个大 if ... elif ... elif ... elif ... else 语句。

我想通了:因为我只需要解析 ClassDefImportFromImport 语句,所以我为 generic_visit 提供了一个不执行任何操作的覆盖方法:

def generic_visit(self, node):
    pass

而不是导致递归的超级 generic_visit。这也大大提高了性能。缺点是只解析模块全局范围内的语句(我认为),但这对我需要的很好。

我最近遇到了这个错误,我想这对你有帮助:

class MyNodeVisitor(ast.NodeVisitor):
    def visit(self, node):
        """Visit a node, no recursively."""
        for node in ast.walk(node):
            method = 'visit_' + node.__class__.__name__
            getattr(self, method, lambda x: x)(node)