代码之家  ›  专栏  ›  技术社区  ›  Ray Brian Agnew

这些奇特的TypeVar的PyCharm生成了什么?

  •  2
  • Ray Brian Agnew  · 技术社区  · 7 年前

    我想实现一个通用字典,将文本键映射到正在或从中继承的类 MyConstrainingClass TypeVar MyDict 分类如下:

    from typing import Mapping, TypeVar
    
    T = TypeVar("T", MyConstrainingClass)
    
    
    class MyDict(Mapping[str, T]):
    

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

    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

    显然,他们描述了“键类型”、“值类型协变”和“类型(?)协变”,但我不知道我是否必须在我的案例中创建这样的通用参数,或者如何定义它们。

    1 回复  |  直到 7 年前
        1
  •  5
  •   Martijn Pieters    7 年前

    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