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

如何让mypy对Protocol实现类的类型检查覆盖泛型工具类场景

解决方案

直接调整Util类的字段类型定义即可满足需求,完整修改后的代码如下:

from dataclasses import dataclass
from typing import Generic, Protocol, Type, TypeVar

T = TypeVar("T")

class MyProto(Protocol):
    attr: str

# 错误实现,不符合协议要求
class Impl:
    attr: int

# 正确实现,符合协议要求
class CorrectImpl:
    attr: str

# 仅修改了Util类的字段类型标注
@dataclass
class Util(Generic[T]):
   proto: Type[T]
   impl: Type[T]

# 案例1 原有正常报错保留
C: Type[MyProto] = Impl 

# 案例2 现在会自动触发mypy报错
util = Util(MyProto, Impl)
# 符合要求的写法不会报错
util_valid = Util(MyProto, CorrectImpl)

验证效果

运行mypy检查会得到两个错误,完全符合预期:

$ mypy t.py
t.py:22: error: Incompatible types in assignment (expression has type "Type[Impl]", variable has type "Type[MyProto]")  [assignment]
t.py:25: error: Argument 2 to "Util" has incompatible type "Type[Impl]"; expected "Type[MyProto]"  [arg-type]
Found 2 errors in 1 file (checked 1 source file)

原理解释

你之前遇到的参数1报错是因为类型标注错误:你传入的MyProto是协议类本身,类型为Type[MyProto],但原来的Util类中proto字段标注为T,二者类型不匹配。
修改后将两个字段都标注为Type[T],mypy会自动根据第一个传入的协议类推断泛型参数T的具体类型,同时自动校验第二个传入的实现类是否满足Type[T]的协议要求,不需要手动指定泛型参数即可触发静态检查。
该方案完全不影响运行时逻辑,你仍然可以正常拿到proto和impl两个类对象做动态注册。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 07:39:04