Mypy:以抽象类作为值的映射的类型注释

dr.*_*ren 5 python type-hinting mypy

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

我们希望能够使用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()}')
Run Code Online (Sandbox Code Playgroud)

运行 mypy-0.501 会出现以下错误:

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

我的问题:我们如何注释映射,backends以便 mypy 理解它只包含 的非抽象子类A

dr.*_*ren 2

根据 Guido 的说法,当合并pull request #2853时,这个问题将在 mypy 的未来版本中得到修复。