能否通过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
相关产品推荐
相关产品推荐

