用 Python 类型注释声明一个通用的 Mapping 子类?

Doc*_*r J 4 python generics annotations mypy

我正在尝试向MappingPython 3.4 中的子类添加泛型类型注释:

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]
Run Code Online (Sandbox Code Playgroud)

我做错了什么,为什么不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"
Run Code Online (Sandbox Code Playgroud)

Doc*_*r J 5

似乎您必须添加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)
Run Code Online (Sandbox Code Playgroud)

在你问之前,mypy 没有Hashable键约束的功能概念(从 0.470 版开始)。[ 1 ] [ 2 ]