python
type_error
ai_generated
true
pydantic_core._pydantic_core.ValidationError: 1 validation error for Settings debug Input should be a valid boolean, unable to interpret input [type=bool_parsing, input_value='yes', input_type=str]
ID: python/pydantic-validation-error-bool-parsing
80%Fix Rate
86%Confidence
0Evidence
2024-07-15First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 2.x | active | — | — | — |
Root Cause
Pydantic v2 only accepts a limited set of boolean-like strings ('true','false','1','0','yes','no','on','off' are case-sensitive to specific forms). 'yes' is not accepted by default.
generic中文
Pydantic v2 只接受有限形式的布尔字符串('true'、'false'、'1'、'0'、'yes'、'no'、'on'、'off',且对大小写敏感)。默认不接受 'yes'。
Workarounds
-
93% success
from pydantic import BaseModel, field_validator class Settings(BaseModel): debug: bool @field_validator('debug', mode='before') @classmethod def parse_bool(cls, v): if isinstance(v, str): return v.lower() in ('yes','true','1','on') return v -
90% success
data['debug'] = str(data['debug']).lower() in ('true','1','yes')
Dead Ends
Common approaches that don't work:
-
95% fail
bool('yes') returns True but bool('false') also returns True because any non-empty string is truthy.
-
99% fail
int('yes') raises ValueError immediately.