python type_error ai_generated true

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

ID: python/pydantic-string-type-coercion-strict

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.x active — — —

Root Cause

A string that cannot be coerced to int was supplied for an int field; Pydantic's lax mode attempts parsing but fails on non-numeric content.

generic

中文

为 int 字段提供了无法转换为整数的字符串,宽松模式尝试解析但遇到非数字内容而失败。

Workarounds

  1. 90% success
    import re
    raw = "8080abc"
    cleaned = re.sub(r"\D", "", raw) or "0"
    cfg = Config(port=int(cleaned))
  2. 88% success
    from pydantic import field_validator
    class Config(BaseModel):
        port: int
        @field_validator("port", mode="before")
        @classmethod
        def clean_port(cls, v):
            if isinstance(v, str):
                v = re.sub(r"\D", "", v)
            return v
  3. 75% success
    from typing import Union
    class Config(BaseModel):
        port: Union[int, str]

Dead Ends

Common approaches that don't work:

  1. 60% fail

    Shifts the failure to a later int() call and loses Pydantic's validation guarantees at the boundary.

  2. 80% fail

    validate_assignment only affects attribute assignment, not constructor validation of input data.

  3. 90% fail

    Raises the same ValueError; the underlying data is genuinely malformed.