python data_error ai_generated true

pydantic.errors.PydanticUndefinedAnnotation: `Node` 未定义

pydantic.errors.PydanticUndefinedAnnotation: `Node` is not defined

ID: python/pydantic-recursion-error-self-referencing

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

版本兼容性

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

根因分析

自引用模型使用了前向引用,但 Pydantic 在构建 schema 时类名尚未进入作用域,无法解析。

English

A self-referencing model uses a forward reference that Pydantic cannot resolve because the class name is not yet in scope during schema building.

generic

解决方案

  1. 95% 成功率
    from typing import Optional
    class Node(BaseModel):
        value: int
        child: Optional["Node"] = None
    Node.model_rebuild()
  2. 90% 成功率
    class Node(BaseModel):
        model_config = ConfigDict(defer_build=True)
        child: Optional["Node"] = None

无效尝试

常见但无效的做法:

  1. 70% 失败

    Loses recursive validation; nested children are not validated and errors propagate silently.

  2. 60% 失败

    Postpones evaluation but Pydantic still needs model_rebuild() to resolve the reference at runtime.

  3. 90% 失败

    Causes duplicate class definitions and Pydantic still cannot resolve the forward ref cleanly.