2017-02-01 10 views
1

私は、Python 3.4でMappingサブクラスにジェネリック型注釈を追加しようとしている:私は間違って何をやっている一般的なマッピングサブクラスをPython型アノテーションで宣言しますか?

from typing import Mapping, TypeVar, Iterator, Dict 

K = TypeVar('K') 
V = TypeVar('V') 


class M(Mapping[K, V]): 
    def __init__(self) -> None: 
     self.d = dict()  # type: Dict[K, V] 

    def __getitem__(self, item: K) -> V: 
     return self.d[item] 

    def __len__(self) -> int: 
     return len(self.d) 

    def __iter__(self) -> Iterator[K]: 
     return iter(self.d) 


# Also errors, but less 
# d = dict() # type: Mapping[K, V] 

、そしてなぜmypyは、より便利なエラーメッセージを与えるものではありませんか?

$ python -V; mypy -V 
Python 3.4.3+ 
mypy 0.470 

$ mypy map.py 
map.py:7: error: Invalid type "map.K" 
map.py:7: error: Invalid type "map.V" 
map.py:9: error: Invalid type "map.K" 
map.py:9: error: Invalid type "map.V" 

答えて

1

明示的な基本クラスとしてGeneric[K, V]を追加する必要があるようです。

from typing import Mapping, TypeVar, Iterator, Dict, Generic 

K = TypeVar('K') 
V = TypeVar('V') 


class M(Generic[K, V], Mapping[K, V]): 
    def __init__(self) -> None: 
     self.d = dict()  # type: Dict[K, V] 

    def __getitem__(self, item: K) -> V: 
     return self.d[item] 

    def __len__(self) -> int: 
     return len(self.d) 

    def __iter__(self) -> Iterator[K]: 
     return iter(self.d) 

そして、あなたが尋ねる前に、mypyは(バージョン0.470のような)キーのHashable制約の機能概念を持っていません。 [1] [2]

関連する問題