python runtime_error ai_generated partial

pydantic_core._pydantic_core.ValidationError: 1 validation error for Node child Recursion error - maximum recursion depth exceeded [type=recursion_loop, input_value={...}, input_type=dict]

ID: python/pydantic-recursion-depth

Also available as: JSON · Markdown · 中文
80%Fix Rate
82%Confidence
0Evidence
2024-08-14First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.x active

Root Cause

A self-referential model (e.g., Node.child: Node) received a cyclic input dict, so validation loops forever.

generic

中文

自引用模型(如 Node.child: Node)接收到循环的输入字典,导致验证陷入无限循环。

Workarounds

  1. 90% success
    def has_cycle(d, seen=None):
        seen = seen or set()
        if id(d) in seen: return True
        seen.add(id(d))
        return any(has_cycle(v, seen) for v in d.values() if isinstance(v, dict))
    assert not has_cycle(payload)
  2. 80% success
    from pydantic import BaseModel, model_validator
    class Node(BaseModel):
        child: 'Node | None' = None
        @model_validator(mode='before')
        @classmethod
        def depth_guard(cls, v, info):
            d = info.context.get('depth', 0) if info.context else 0
            if d > 50: raise ValueError('too deep')
            return v

Dead Ends

Common approaches that don't work:

  1. 75% fail

    Turns the loop into a segfault instead of a clean ValidationError.

  2. 55% fail

    Disables nested validation entirely; malformed children pass silently.

  3. 50% fail

    The error is raised as ValidationError; the except clause never fires.