python data_error ai_generated partial

pydantic_core._pydantic_core.ValidationError: 1 个验证错误,检测到循环引用递归错误 [类型=recursion_loop]

pydantic_core._pydantic_core.ValidationError: 1 validation error for Node children.0.parent Recursion error - cyclic reference detected [type=recursion_loop]

ID: python/pydantic-recursion-loop-detected

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

版本兼容性

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

根因分析

输入数据包含循环引用(例如对象引用自身),Pydantic 在验证递归模型时检测到该循环。

English

The input data contains a cyclic reference (e.g. an object referencing itself), which Pydantic detects while validating a recursive model.

generic

解决方案

  1. 90% 成功率
    def strip_parent(node):
        node.pop('parent', None)
        for c in node.get('children', []):
            strip_parent(c)
        return node
    Node.model_validate(strip_parent(data))
  2. 80% 成功率
    from pydantic import BaseModel
    
    class Node(BaseModel):
        name: str
        children: list['Node'] = []
    
    Node.model_rebuild()  # avoid modeling parent back-references

无效尝试

常见但无效的做法:

  1. 85% 失败

    The cycle is in the data itself, not stack depth. It will still be detected and may crash the interpreter.

  2. 70% 失败

    Loses the schema definition and breaks legitimate nested validation for non-cyclic inputs.