python runtime_error ai_generated partial

pydantic_core._pydantic_core.ValidationError:1 个验证错误(Node) child 递归错误——超过最大递归深度 [type=recursion_loop, input_value={...}, input_type=dict]

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

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

版本兼容性

版本状态引入弃用备注
2.x active

根因分析

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

English

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

generic

解决方案

  1. 90% 成功率
    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% 成功率
    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

无效尝试

常见但无效的做法:

  1. 75% 失败

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

  2. 55% 失败

    Disables nested validation entirely; malformed children pass silently.

  3. 50% 失败

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