python runtime_error ai_generated true

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

ID: python/pytest-assertion-repr-recursion

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2024-10-30First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
7.x active — — —
8.x active — — —

Root Cause

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

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 90% fail

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

  2. 95% fail

    Silently passes tests; hides real failures.

  3. 70% fail

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