python config_error ai_generated true

pydantic.errors.PydanticUserError: 检测到未注解的属性:`children = []`。所有模型字段都需要类型注解;若 `children` 不是字段,可将其注解为 `ClassVar` 或更新 `model_config['ignored_types']`。

pydantic.errors.PydanticUserError: A non-annotated attribute was detected: `children = []`. All model fields require a type annotation; if `children` is not meant to be a field, you may be able to resolve this error by annotating it as a `ClassVar` or updating `model_config['ignored_types']`.

ID: python/pydantic-recursion-loop-model

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

版本兼容性

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

根因分析

Pydantic v2 中,没有类型注解的类级赋值会被当作字段,即使原意为常量或辅助变量。

English

A class-level assignment without a type annotation is treated as a field in Pydantic v2, even if it was intended as a constant or helper.

generic

解决方案

  1. 95% 成功率
    Annotate as ClassVar: `from typing import ClassVar
    children: ClassVar[list] = []`
  2. 92% 成功率
    Add a type annotation: `children: list[Node] = []` if it really is a field (use `Field(default_factory=list)`).

无效尝试

常见但无效的做法:

  1. 60% 失败

    Setting the attribute inside `__init__` instead of at class level changes semantics and breaks serialization.

  2. 40% 失败

    Adding `ClassVar` but keeping the mutable default still shares state across instances.