python
runtime_error
ai_generated
partial
pydantic_core._pydantic_core.ValidationError: 1 validation error for Node children.0.children.0 RecursionError: maximum recursion depth exceeded while calling a Python object
ID: python/pydantic-recursion-error-self-referential
80%Fix Rate
82%Confidence
0Evidence
2025-01-19First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 2.x | active | — | — | — |
Root Cause
A self-referential Pydantic model (tree/graph) was given a cyclic data structure, causing infinite recursion during validation. Pydantic has no built-in cycle detection for plain nested models.
generic中文
自引用 Pydantic 模型(树/图)接收到循环数据结构,导致验证时无限递归。Pydantic 对普通嵌套模型没有内置的循环检测。
Workarounds
-
85% success
def break_cycles(obj, seen=None): seen = seen or set() if id(obj) in seen: return None seen.add(id(obj)) if isinstance(obj, dict): return {k: break_cycles(v, seen) for k, v in obj.items()} if isinstance(obj, list): return [break_cycles(v, seen) for v in obj] return obj Node.model_validate(break_cycles(raw)) -
70% success
from pydantic import BaseModel, field_validator class Node(BaseModel): name: str children: list['Node'] = [] @field_validator('children') @classmethod def limit_depth(cls, v): if len(v) > 100: raise ValueError('tree too deep') return v
Dead Ends
Common approaches that don't work:
-
80% fail
This only defers the crash; a truly cyclic structure will still exhaust memory and eventually segfault the interpreter.
-
90% fail
arbitrary_types_allowed permits non-Pydantic types, it does not detect or prevent cyclic references.