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

Also available as: JSON · Markdown · 中文
80%Fix Rate
82%Confidence
0Evidence
2025-01-19First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
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

  1. 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))
  2. 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:

  1. 80% fail

    This only defers the crash; a truly cyclic structure will still exhaust memory and eventually segfault the interpreter.

  2. 90% fail

    arbitrary_types_allowed permits non-Pydantic types, it does not detect or prevent cyclic references.