Mypy:以抽象 类 作为值的地图类型注释

Mypy: type annotation for map with abstract classes as values

我正在开发一个具有各种存储后端的框架。这些后端都实现了一个抽象基础class。后端 classes 存储在从后端名称到实现该后端的 class 的映射中。

我们希望能够用mypy进行类型检查,注释如下:

#!python
import abc
import typing


class A(metaclass=abc.ABCMeta):  # The abstract base class
    def __init__(self, name: str) -> None:
        self.name = name

    @abc.abstractmethod
    def get_name(self):
        pass


class B(A):  # Some non-abstract backend
    def get_name(self):
        return f'B: {self.name}'


class C(A):  # Another non-abstract backend
    def get_name(self):
        return f'C: {self.name}'


backends: typing.Mapping[str, typing.Type[A]] = {
    'backend-b': B,
    'backend-c': C,
}


if __name__ == '__main__':
    backend_cls = backends['backend-c']
    # The following line causes an error with mypy:
    instance = backend_cls('demo-name')
    print(f'Name is: {instance.get_name()}')

运行 mypy-0.501 给出了这个错误:

typingtest.py:32: error: Cannot instantiate abstract class 'A' with abstract attribute 'get_name'

我的问题: 我们如何注释映射 backends 以便 mypy 理解它只包含 [=14 的非抽象子 classes =]?

According to Guido, this is something that'll be fixed in a future version of mypy, when pull request #2853 被合并。