【问题标题】:Mypy: type annotation for map with abstract classes as valuesMypy:以抽象类为值的地图类型注释
【发布时间】:2017-08-14 15:48:38
【问题描述】:

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

我们希望能够用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 理解它只包含A 的非抽象子类?

【问题讨论】:

    标签: python type-hinting mypy


    【解决方案1】:

    According to Guido,当 pull request #2853 合并时,这将在 mypy 的未来版本中修复。

    【讨论】:

      猜你喜欢
      • 2017-05-03
      • 1970-01-01
      • 2020-01-24
      • 1970-01-01
      • 2021-03-01
      • 2021-07-24
      • 2014-02-19
      • 2023-03-10
      • 2019-11-13
      相关资源
      最近更新 更多