python type_error ai_generated true

pydantic_core._pydantic_core.ValidationError: 设置模型验证错误:debug 字段无法解析为布尔值

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

其他格式: JSON · Markdown 中文 · English
80%修复率
86%置信度
0证据数
2024-07-15首次发现

版本兼容性

版本状态引入弃用备注
2.x active — — —

根因分析

Pydantic v2 只接受有限形式的布尔字符串('true'、'false'、'1'、'0'、'yes'、'no'、'on'、'off',且对大小写敏感)。默认不接受 'yes'。

English

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

解决方案

  1. 93% 成功率
    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
  2. 90% 成功率
    data['debug'] = str(data['debug']).lower() in ('true','1','yes')

无效尝试

常见但无效的做法:

  1. 95% 失败

    bool('yes') returns True but bool('false') also returns True because any non-empty string is truthy.

  2. 99% 失败

    int('yes') raises ValueError immediately.