python type_error ai_generated true

pydantic_core._pydantic_core.ValidationError: 1 个验证错误 (Model) age 输入应为有效整数,无法将字符串解析为整数 [type=int_parsing, input_value='abc', input_type=str]

pydantic_core._pydantic_core.ValidationError: 1 validation error for Model age Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='abc', input_type=str]

ID: python/pydantic-type-error-int-parsing-string

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

版本兼容性

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

根因分析

Pydantic v2 更严格的解析会拒绝非数字字符串赋给 `int` 字段,而 v1 会静默转换或抛出不同消息。

English

Pydantic v2's stricter parsing rejects non-numeric strings for `int` fields where v1 would silently coerce or raise a different message.

generic

解决方案

  1. 90% 成功率
    Use a custom validator: `@field_validator('age', mode='before')
    @classmethod
    def parse_age(cls, v):
        return int(v) if str(v).isdigit() else 0`
  2. 88% 成功率
    Change the field type to `Union[int, str]` and validate downstream, or use `Annotated[int, BeforeValidator(lambda v: int(v) if str(v).isdigit() else 0)]`.

无效尝试

常见但无效的做法:

  1. 75% 失败

    Wrapping in `try/except ValueError` does not catch `ValidationError` in v2 because it is a separate exception type.

  2. 60% 失败

    Using `int(value)` before passing to the model defeats the purpose and still raises for non-numeric input.