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

使用Pydantic泛型时出现mypy类型错误,求原因排查

使用Pydantic泛型模型时Mypy类型检查报错

项目配置(pyproject.toml)

[tool.poetry]
name = "test"
version = "0.1.0"
description = ""
authors = ["Joe Smith <joe.smith@example.com>"]

[tool.poetry.dependencies]
python = "^3.11"
pydantic = "^1.10.7"
mypy = "^1.3.0"

[tool.mypy]
plugins = [
    "pydantic.mypy"
]

[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"

代码示例

from typing import Generic, TypeVar

from pydantic.generics import GenericModel

T = TypeVar("T")


class BaseModel(GenericModel, Generic[T]):
    data: T


class StringModel(BaseModel[str]):
    pass


model = StringModel(data="data")
model.data = "other data"

Mypy报错信息

error: Incompatible types in assignment (expression has type "str", variable has type "T")  [assignment]
    model.data = "other data"
                 ^~~~~~~~~~~~

问题排查与解决

测试后确认,该类型错误由pydantic.mypy插件引发,移除Mypy配置中的该插件后,报错不再出现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 00:15:19