【问题标题】:RuntimeError: maximum recursion depth exceeded while calling a Python object with astRuntimeError:使用 ast 调用 Python 对象时超出最大递归深度
【发布时间】:2015-05-07 16:43:02
【问题描述】:

我正在使用 ast 从 Python 源文件中获取信息(根据建议 here)。为此,我扩展了ast.NodeVisitor,它在大多数源文件中运行良好。但是,我得到了一个

RuntimeError: maximum recursion depth exceeded while calling a Python object

当我在大班上使用这个时例外(~2000 行。糟糕的练习。我知道 :))。当我在崩溃时检查堆栈时,我看到确实有一个非常深的递归正在进行,但它似乎并没有进入循环。即,如果递归会继续下去,它将成功完成。有没有办法解决这个问题?

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

【问题讨论】:

  • Downvoter(s):对您投反对票的为什么进行简短评论会更有帮助。

标签: python python-2.7 recursion abstract-syntax-tree


【解决方案1】:

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

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)

【讨论】:

    【解决方案2】:

    我想通了:因为我只需要解析ClassDefImportFromImport 语句,我给generic_visit 提供了一个什么都不做的覆盖方法:

    def generic_visit(self, node):
        pass
    

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

    【讨论】:

      猜你喜欢
      • 2011-05-31
      • 2016-04-01
      • 2011-12-01
      • 2013-08-29
      • 2016-12-23
      • 2012-12-22
      • 2017-03-18
      • 2015-04-15
      • 1970-01-01
      相关资源
      最近更新 更多