python type_error ai_generated true

pydantic_core._pydantic_core.ValidationError: Config 校验失败 port 输入应为有效整数,无法将字符串解析为整数 [type=int_parsing]

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

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

版本兼容性

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

根因分析

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

English

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

解决方案

  1. 90% 成功率
    import re
    raw = "8080abc"
    cleaned = re.sub(r"\D", "", raw) or "0"
    cfg = Config(port=int(cleaned))
  2. 88% 成功率
    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% 成功率
    from typing import Union
    class Config(BaseModel):
        port: Union[int, str]

无效尝试

常见但无效的做法:

  1. 60% 失败

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

  2. 80% 失败

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

  3. 90% 失败

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