2017-03-22 111 views
2

我正在使用各種存儲後端的框架。這些後端都實現了一個抽象基類。後端類存儲在從後端名稱到實現該後端的類的映射中。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()}') 

運行mypy-0.501給出了這樣的錯誤:

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

我的問題:我們如何註釋映射backends,使mypy理解它只包含A的非抽象子類?

回答