python type_error ai_generated true

pydantic.errors.UnionError: 无法为联合类型验证输入

pydantic.errors.UnionError: Unable to validate input for union

ID: python/pydantic-union-type-validation

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

版本兼容性

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

根因分析

当字段类型为 Union[A, B] 时,Pydantic 会按顺序尝试每种类型;如果都不匹配,就会抛出 UnionError,通常是由于类型歧义或严格验证。

English

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

解决方案

  1. 90% 成功率
    Use discriminated unions with Literal types: Field(discriminator='type')
  2. 85% 成功率
    Define a custom validator to handle complex union logic

无效尝试

常见但无效的做法:

  1. 70% 失败

    Order matters; if first type accepts too broadly, it may consume valid inputs for second type.

  2. 60% 失败

    Optional[Union] can still fail if input is None but not allowed.