python
type_error
ai_generated
true
pydantic_core._pydantic_core.ValidationError: 1 validation error for User 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-validation-error-model-type
80%Fix Rate
88%Confidence
0Evidence
2024-03-12First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 2.x | active | — | — | — |
Root Cause
Pydantic v2 strict-by-default coercion fails when a string like 'abc' is passed to an int field; the type coercion cannot parse non-numeric strings.
generic中文
Pydantic v2 默认严格模式下,将非数字字符串 'abc' 传入 int 字段时会因无法解析而抛出验证错误。
Workarounds
-
92% success
from pydantic import BaseModel, field_validator class User(BaseModel): age: int @field_validator('age', mode='before') @classmethod def parse_age(cls, v): if isinstance(v, str) and not v.isdigit(): raise ValueError('age must be numeric') return int(v) -
95% success
from pydantic import ValidationError try: User(age='abc') except ValidationError as e: return {'errors': e.errors()}, 422
Dead Ends
Common approaches that don't work:
-
75% fail
strict=False still refuses to parse 'abc' into int because no valid numeric representation exists.
-
60% fail
This hides the error but downstream code expecting int will crash with TypeError.