python data_error ai_generated true

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-06-12First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.x active — — —

Root Cause

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

中文

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

Workarounds

  1. 85% success
    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% success
    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

Dead Ends

Common approaches that don't work:

  1. 90% fail

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

  2. 75% fail

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

  3. 60% fail

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