python
data_error
ai_generated
true
pydantic.errors.PydanticUndefinedAnnotation: `Node` is not defined
ID: python/pydantic-recursion-error-self-referencing
80%Fix Rate
86%Confidence
0Evidence
2024-07-11First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 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
-
95% success
from typing import Optional class Node(BaseModel): value: int child: Optional["Node"] = None Node.model_rebuild() -
90% success
class Node(BaseModel): model_config = ConfigDict(defer_build=True) child: Optional["Node"] = None
Dead Ends
Common approaches that don't work:
-
70% fail
Loses recursive validation; nested children are not validated and errors propagate silently.
-
60% fail
Postpones evaluation but Pydantic still needs model_rebuild() to resolve the reference at runtime.
-
90% fail
Causes duplicate class definitions and Pydantic still cannot resolve the forward ref cleanly.