python
type_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='abc', input_type=str]
ID: python/pydantic-type-error-int-parsing-string
80%Fix Rate
89%Confidence
0Evidence
2024-06-05First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 2.x | active | — | — | — |
Root Cause
Pydantic v2's stricter parsing rejects non-numeric strings for `int` fields where v1 would silently coerce or raise a different message.
generic中文
Pydantic v2 更严格的解析会拒绝非数字字符串赋给 `int` 字段,而 v1 会静默转换或抛出不同消息。
Workarounds
-
90% success
Use a custom validator: `@field_validator('age', mode='before') @classmethod def parse_age(cls, v): return int(v) if str(v).isdigit() else 0` -
88% success
Change the field type to `Union[int, str]` and validate downstream, or use `Annotated[int, BeforeValidator(lambda v: int(v) if str(v).isdigit() else 0)]`.
Dead Ends
Common approaches that don't work:
-
75% fail
Wrapping in `try/except ValueError` does not catch `ValidationError` in v2 because it is a separate exception type.
-
60% fail
Using `int(value)` before passing to the model defeats the purpose and still raises for non-numeric input.