python
type_error
ai_generated
true
pydantic_core._pydantic_core.ValidationError:1 个验证错误(Payload) name 输入应为有效的字符串 [type=string_type, input_value=123, input_type=int]
pydantic_core._pydantic_core.ValidationError: 1 validation error for Payload name Input should be a valid string [type=string_type, input_value=123, input_type=int]
ID: python/pydantic-strict-str-from-int
80%修复率
86%置信度
0证据数
2024-06-02首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 2.x | active | — | — | — |
根因分析
model_config 的 strict=True(或 StrictStr)阻止将 int 强制转换为 str,尽管 v1 允许这样做。
English
model_config strict=True (or StrictStr) prevents coercion of int to str, even though v1 allowed it.
解决方案
-
90% 成功率
from pydantic import BaseModel, field_validator class Payload(BaseModel): model_config = {'strict': True} name: str @field_validator('name', mode='before') @classmethod def to_str(cls, v): return str(v) -
85% 成功率
class Payload(BaseModel): name: int | str @field_validator('name') @classmethod def norm(cls, v): return str(v)
无效尝试
常见但无效的做法:
-
40% 失败
Changes semantics only for that field; other numeric-to-string coercions still fail.
-
50% 失败
Every caller must remember; easy to miss in one code path.
-
55% 失败
Disables strictness everywhere, re-introducing silent coercions you wanted to avoid.