python
type_error
ai_generated
true
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%Fix Rate
86%Confidence
0Evidence
2024-06-02First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 2.x | active | — | — | — |
Root Cause
model_config strict=True (or StrictStr) prevents coercion of int to str, even though v1 allowed it.
generic中文
model_config 的 strict=True(或 StrictStr)阻止将 int 强制转换为 str,尽管 v1 允许这样做。
Workarounds
-
90% success
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% success
class Payload(BaseModel): name: int | str @field_validator('name') @classmethod def norm(cls, v): return str(v)
Dead Ends
Common approaches that don't work:
-
40% fail
Changes semantics only for that field; other numeric-to-string coercions still fail.
-
50% fail
Every caller must remember; easy to miss in one code path.
-
55% fail
Disables strictness everywhere, re-introducing silent coercions you wanted to avoid.