You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pydantic子类字段类型验证异常:子类实例赋值父类字段报错求助

Pydantic验证QueryParams子类实例时出现意外错误

我需要在Pydantic模型中验证一个字段,要求其取值必须是QueryParams的子类实例——具体子类会动态变化,但始终继承自该父类。但实际使用中,子类实例却触发了本不该出现的验证错误,我已在相关GitHub仓库提交Bug报告。

复现代码

from fastapi.datastructures import QueryParams
from pydantic import ConfigDict, Field, BaseModel
from humbldata.core.standard_models.abstract.humblobject import HumblObject
from humbldata.core.standard_models.toolbox import ToolboxQueryParams
from humbldata.core.standard_models.toolbox.technical.mandelbrot_channel import MandelbrotChannelQueryParams


class Model(BaseModel):
    model_config = ConfigDict(arbitrary_types_allowed=True)
    command_params: QueryParams = Field()

    # @field_validator("command_params")
    # def validate_command_params(cls, v):
    #     if issubclass(type(v), QueryParams):
    #         return v
    #     raise TypeError("Wrong type for 'command_params', must be subclass of QueryParams")


Model(command_params=MandelbrotChannelQueryParams())

报错信息

---------------------------------------------------------------------------
ValidationError                           Traceback (most recent call last)
Cell In[23], line 19
     10     command_params: QueryParams = Field()
     12     # @field_validator("command_params")
     13     # def validate_command_params(cls, v):
     14     #     if issubclass(type(v), QueryParams):
     15     #         return v
     16     #     raise TypeError("Wrong type for 'command_params', must be subclass of QueryParams")
---> 19 Model(command_params=MandelbrotChannelQueryParams())

File c:\Users\jjfan\github\humblFINANCE-org\humbldata\menv\Lib\site-packages\pydantic\main.py:171, in BaseModel.__init__(self, **data)
    169 # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    170 __tracebackhide__ = True
---> 171 self.__pydantic_validator__.validate_python(data, self_instance=self)

ValidationError: 1 validation error for Model
command_params
  Input should be an instance of QueryParams [type=is_instance_of, input_value=MandelbrotChannelQueryPar...False, live_price=False), input_type=MandelbrotChannelQueryParams]
    For further information visit https://errors.pydantic.dev/2.6/v/is_instance_of

临时解决方案

目前可以通过启用自定义字段验证器来绕过这个问题,验证器会检查输入是否是QueryParams的子类实例:

from pydantic import field_validator

class Model(BaseModel):
    model_config = ConfigDict(arbitrary_types_allowed=True)
    command_params: QueryParams = Field()

    @field_validator("command_params")
    def validate_command_params(cls, v):
        if issubclass(type(v), QueryParams):
            return v
        raise TypeError("Wrong type for 'command_params', must be subclass of QueryParams")

内容的提问来源于stack exchange,提问作者JJ Fantini

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 12:34:58