python type_error ai_generated true

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

ID: python/pydantic-validation-error-int-parsing

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.x active — — —

Root Cause

A string value containing a decimal or non-numeric characters was passed to an int-typed field. Pydantic v2 strict parsing rejects strings like '19.99' for int fields.

generic

中文

向 int 类型字段传入了包含小数或非数字字符的字符串。Pydantic v2 严格解析会拒绝 '19.99' 这类字符串赋值给 int 字段。

Workarounds

  1. 95% success
    from decimal import Decimal
    from pydantic import BaseModel
    
    class Product(BaseModel):
        price: Decimal
  2. 90% success
    from pydantic import BaseModel, field_validator
    
    class Product(BaseModel):
        price: int
    
        @field_validator('price', mode='before')
        @classmethod
        def parse_price(cls, v):
            return int(float(v))

Dead Ends

Common approaches that don't work:

  1. 90% fail

    int('19.99') raises ValueError because Python cannot directly cast a decimal string to int.

  2. 60% fail

    Loses numeric semantics; downstream arithmetic operations will fail with TypeError.