python data_error ai_generated true

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

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2024-07-11First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.x active — — —

Root Cause

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

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 70% fail

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

  2. 60% fail

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

  3. 90% fail

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