这些花哨的 TypeVar 的 PyCharm 生成了什么?

What are these fancy TypeVar's PyCharm generates?

我想实现一个通用字典,将文本键映射到 class 是或继承自 MyConstrainingClass,所以我声明了 TypeVarMyDict class如下:

from typing import Mapping, TypeVar

T = TypeVar("T", MyConstrainingClass)


class MyDict(Mapping[str, T]):

当我接受 PyCharm 的建议来实现抽象基础 class 方法时,它会生成以下输出:

class MyList(Mapping[str, T]):
    def __getitem__(self, k: _KT) -> _VT_co:
        pass

    def __iter__(self) -> Iterator[_T_co]:
        pass

    def __len__(self) -> int:
        pass

那些 _KT_VT_co_T_co 泛型类型变量是什么?我没有在任何地方自己定义它们,它似乎是从超级 class.

中获取的

显然他们描述了 "KeyType"、"ValueType covariant" 和 "Type (?) covariant",但我完全不知道我是否必须在我的案例中创建此类通用参数或如何定义它们。

PyCharm 从 Mapping declaration in the typing module(或他们自己的文件内部版本)中获取它们:

class Mapping(Collection[KT], Generic[KT, VT_co],
              extra=collections_abc.Mapping):
    __slots__ = ()

T_co 协变从基数 类 进一步继承自 Iterable)。

我会用您更具体的版本替换这些建议:

class MyList(Mapping[str, T]):
    def __getitem__(self, k: str) -> T:
        pass

    def __iter__(self) -> Iterator[str]:
        pass

    def __len__(self) -> int:
        pass