python data_error ai_generated true

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='twenty', input_type=str]

ID: python/pydantic-int-parsing-string

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.x active

Root Cause

A string like 'twenty' or '12.5' was passed to an int field. Pydantic v2 strict parsing refuses to coerce non-numeric strings.

generic

中文

向 int 字段传入了诸如 'twenty' 或 '12.5' 的字符串。Pydantic v2 的严格解析拒绝强制转换非数字字符串。

Workarounds

  1. 90% success
    from pydantic import BaseModel, field_validator
    class M(BaseModel):
        age: int
        @field_validator('age', mode='before')
        @classmethod
        def coerce(cls, v):
            if isinstance(v, str) and v.isdigit():
                return int(v)
            return v
  2. 85% success
    from fastapi import FastAPI, HTTPException
    from pydantic import ValidationError
    try:
        M(**payload)
    except ValidationError as e:
        raise HTTPException(422, e.errors())

Dead Ends

Common approaches that don't work:

  1. 62% fail

    int() raises ValueError inside validators, producing a confusing 500 rather than a clean ValidationError.

  2. 48% fail

    strict=False still won't parse 'twenty' into an int; it only relaxes numeric-string coercion of digits.

  3. 35% fail

    Loses field-level detail and downstream code relying on .errors() breaks.