python
type_error
ai_generated
true
pydantic.errors.UnionError: Unable to validate input for union
ID: python/pydantic-union-type-validation
80%Fix Rate
83%Confidence
0Evidence
2024-05-05First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 2.x | active | — | — | — |
Root Cause
When a field is typed as Union[A, B], Pydantic tries each type in order; if none match, it raises UnionError, often due to ambiguous types or strict validation.
generic中文
当字段类型为 Union[A, B] 时,Pydantic 会按顺序尝试每种类型;如果都不匹配,就会抛出 UnionError,通常是由于类型歧义或严格验证。
Workarounds
-
90% success
Use discriminated unions with Literal types: Field(discriminator='type')
-
85% success
Define a custom validator to handle complex union logic
Dead Ends
Common approaches that don't work:
-
70% fail
Order matters; if first type accepts too broadly, it may consume valid inputs for second type.
-
60% fail
Optional[Union] can still fail if input is None but not allowed.