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

Pydantic模型提示不可调用:传入类作为参数时类型校验报错

问题原因与解决方法

错误原因

你给validate_data函数的validator参数标注的类型是CustomModel,这意味着类型检查器(pyright/mypy)认为这个参数应该接收CustomModel的实例对象,但你实际调用时传的是CustomModel类本身。实例对象无法像类那样通过(**custom_dict)的方式创建新实例,所以触发了'"CustomModel" not callable'的错误。

解决方法

需要把validator的类型标注改为Type[CustomModel],这个类型明确表示参数接收的是CustomModel类或它的子类,而非实例。

修改后的完整代码:

from pydantic import BaseModel
from typing import Type

class CustomModel(BaseModel):
    field1: int
    field2: str

def validate_data(validator: Type[CustomModel], custom_dict: dict) -> None:
    cm = validator(**custom_dict)

# 调用方式保持不变
custom_dict = {"field1": 1, "field2": "test"}
x = validate_data(validator=CustomModel, custom_dict=custom_dict)

补充说明

直接写CustomModel(**custom_dict)不会报错,是因为类型检查器明确知道CustomModel是可调用的类构造器;而当你把类传给标注为实例类型的参数时,类型检查器会判定类型不匹配,且实例不具备构造新对象的调用能力,因此报错。

内容的提问来源于stack exchange,提问作者swats-the-floran

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 14:03:12