python
data_error
ai_generated
true
pydantic_core._pydantic_core.ValidationError: 标签联合类型校验失败,kind 字段应为 'cat',实际为 'dog'
pydantic_core._pydantic_core.ValidationError: 3 validation errors for TaggedUnion cat.kind Input should be 'cat' [type=literal_error, input_value='dog', input_type=str]
ID: python/pydantic-union-tag-discriminator-error
80%修复率
84%置信度
0证据数
2024-09-03首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 2.x | active | — | — | — |
根因分析
使用 Literal 判别器的可辨识联合收到一个不匹配任何联合成员的标签值,导致每个分支都校验失败。
English
A discriminated union with a Literal discriminator received a tag value that does not match any union member, so every branch fails validation.
解决方案
-
90% 成功率
kind = data.get('kind') mapping = {'cat': Cat, 'dog': Dog} if kind not in mapping: raise ValueError(f'unknown kind: {kind}') obj = mapping[kind].model_validate(data) -
85% 成功率
from typing import Annotated from pydantic import BeforeValidator Normalize = Annotated[str, BeforeValidator(lambda v: v.lower())] class Cat(BaseModel): kind: Literal['cat'] name: Normalize
无效尝试
常见但无效的做法:
-
65% 失败
Falls back to slow smart-union matching and produces confusing errors when multiple members overlap.
-
80% 失败
Discriminator requires all Literal values to be unique; a str member makes the union ambiguous and Pydantic raises at build time.