如何为实现同一接口的Python类添加正确类型提示规避MyPy报错
要标注类本身而非实例,需要用Type[](Python 3.9+可直接用内置type[])包装你的抽象基类类型即可。
修改后的完整可通过MyPy检查的代码如下:
import abc from typing import Type class Interface(abc.ABC): @abc.abstractmethod @classmethod def make(cls): ... class AObject(Interface): def __init__(self, a: int): self.a = a @classmethod def make(cls): return cls(a=3) class BObject(Interface): def __init__(self, b: int): self.b = b @classmethod def make(cls): return cls(b=3) # 仅修改此处的类型注解即可 data: tuple[Type[Interface], ...] = (AObject, BObject)
该注解的效果:
- 变量
data仅可存入继承了Interface的类,存入不符合要求的类时MyPy会直接抛出赋值错误 - 调用类上的
make方法时可被正常校验,比如data[0].make()不会报方法不存在的错误,返回值类型也能被正确推导
如果不需要运行时的抽象基类继承校验,仅希望静态检查类是否存在make类方法,也可以用Protocol定义结构类型:
from typing import Protocol, Type class Makeable(Protocol): @classmethod def make(cls): ... # 不需要显式继承,只要类有make类方法就符合类型要求 data: tuple[Type[Makeable], ...] = (AObject, BObject)
内容的提问来源于stack exchange,提问作者Levik
相关产品推荐
相关产品推荐

