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

其他格式: JSON · Markdown 中文 · English
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.

generic

解决方案

  1. 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)
  2. 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

无效尝试

常见但无效的做法:

  1. 65% 失败

    Falls back to slow smart-union matching and produces confusing errors when multiple members overlap.

  2. 80% 失败

    Discriminator requires all Literal values to be unique; a str member makes the union ambiguous and Pydantic raises at build time.