python runtime_error ai_generated partial

pydantic_core._pydantic_core.ValidationError: 1 个验证错误,递归深度超过 Python 最大限制

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

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

版本兼容性

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

根因分析

自引用 Pydantic 模型(树/图)接收到循环数据结构,导致验证时无限递归。Pydantic 对普通嵌套模型没有内置的循环检测。

English

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

解决方案

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

无效尝试

常见但无效的做法:

  1. 80% 失败

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

  2. 90% 失败

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