python runtime_error ai_generated true

RecursionError:调用 Python 对象时超出最大递归深度 (在对自引用对象进行断言内省期间)

RecursionError: maximum recursion depth exceeded while calling a Python object (during assertion introspection of a self-referential object)

ID: python/pytest-assertion-repr-recursion

其他格式: JSON · Markdown 中文 · English
80%修复率
84%置信度
0证据数
2024-10-30首次发现

版本兼容性

版本状态引入弃用备注
7.x active — — —
8.x active — — —

根因分析

在 assert 中比较的对象具有无限递归的 __repr__(例如子节点包含自身的树节点),而 pytest 的断言重写调用 repr 生成差异。

English

An object compared in an assert has a __repr__ that recurses infinitely (e.g., a tree node whose children include itself), and pytest's assertion rewriting calls repr for the diff.

generic

解决方案

  1. 95% 成功率
    class Node:
        def __repr__(self):
            return f"Node(id={id(self)}, value={self.value!r})"
  2. 90% 成功率
    assert node.value == expected.value
    assert node.parent_id == expected.parent_id

无效尝试

常见但无效的做法:

  1. 90% 失败

    May segfault the interpreter and doesn't fix the cyclic repr.

  2. 95% 失败

    Silently passes tests; hides real failures.

  3. 70% 失败

    Loses all diff quality; the repr still recurses when printed.