python
data_error
ai_generated
true
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%Fix Rate
84%Confidence
0Evidence
2024-09-03First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 2.x | active | — | — | — |
Root Cause
A discriminated union with a Literal discriminator received a tag value that does not match any union member, so every branch fails validation.
generic中文
使用 Literal 判别器的可辨识联合收到一个不匹配任何联合成员的标签值,导致每个分支都校验失败。
Workarounds
-
90% success
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% success
from typing import Annotated from pydantic import BeforeValidator Normalize = Annotated[str, BeforeValidator(lambda v: v.lower())] class Cat(BaseModel): kind: Literal['cat'] name: Normalize
Dead Ends
Common approaches that don't work:
-
65% fail
Falls back to slow smart-union matching and produces confusing errors when multiple members overlap.
-
80% fail
Discriminator requires all Literal values to be unique; a str member makes the union ambiguous and Pydantic raises at build time.