python data_error ai_generated true

pydantic_core._pydantic_core.ValidationError: 1 个验证错误,字段 age 输入应为有效整数,无法将字符串解析为整数

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

ID: python/pydantic-validation-error-input-type

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

版本兼容性

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

根因分析

Pydantic v2 严格类型转换:声明为 int 的字段收到了字符串,且该字符串不是数字字面量,因此 Pydantic 拒绝转换。与 v1 不同,v2 默认不再将任意字符串静默转换为整数。

English

Pydantic v2 strict type coercion: a string field was passed where an int was declared, and the string is not a numeric literal so Pydantic refuses to coerce it. Unlike v1, v2 no longer silently coerces arbitrary strings to ints by default.

generic

解决方案

  1. 85% 成功率
    from pydantic import BaseModel, field_validator
    
    class User(BaseModel):
        age: int
    
        @field_validator('age', mode='before')
        @classmethod
        def parse_age(cls, v):
            if isinstance(v, str) and v.isalpha():
                words = {'twenty': 20, 'thirty': 30}
                return words.get(v.lower(), v)
            return v
  2. 80% 成功率
    from typing import Union
    from pydantic import BaseModel, BeforeValidator
    from typing_extensions import Annotated
    
    CoercedInt = Annotated[int, BeforeValidator(lambda v: int(v) if str(v).isdigit() else v)]
    
    class User(BaseModel):
        age: CoercedInt

无效尝试

常见但无效的做法:

  1. 90% 失败

    Silently swallowing ValidationError means the invalid object never gets constructed; downstream code receives None or crashes with AttributeError later.

  2. 75% 失败

    strict=False only relaxes some coercions; 'twenty' is not a valid integer representation and will still raise int_parsing.

  3. 60% 失败

    v1 also raises for non-numeric strings like 'twenty'; the behavior difference is only for numeric-looking strings such as '25'.