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

能否通过mypy为接收cls而非self参数的方法添加类型提示?

让mypy正确识别类中接收cls而非self参数的方法

典型使用场景

  • 给SQLAlchemy的hybrid_property的.expression装饰器添加类型标注
  • 实现自定义的非内置版本classmethod装饰器

直接添加类型注解的报错问题

直接给cls参数加显式Type类型注解无法通过mypy校验,复现代码如下:

from typing import Type

class Example:
  @my_custom_classmethod
  def foo(cls: Type["Example"]) -> str:
    return "doesn't work"

此时mypy会抛出固定报错:

The erased type of self "Type[Example]" is not a supertype of its class "Example"

这个报错的校验逻辑在普通实例方法场景下成立,但无法适配自定义类方法的特殊场景。

可用临时方案

目前可正常运行的临时兼容方案是在方法签名行尾添加# type: ignore注释:

class Example:
  @my_custom_classmethod
  def foo(cls: Type["Example"]) -> str: # type: ignore
    return "this actually kind of does work!"

方案实际表现

  • 方法体内的cls能获得正确的类型推断
  • 装饰器接收到的方法类型符合预期
  • 存在缺陷:属于hack式写法,不够规范优雅。

内容的提问来源于stack exchange,提问作者Alan O'Donnell

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 05:54:36