打字,自定义集合类型

Typing, custom collection type

输入模块提供了一些方便的功能,以提高可读性并增强对输入代码正确性的信心。

最好的功能之一是您可以编写如下内容来描述具有指定元素类型的输入字典。

def myFun(inputDict:Dict[str, int]): pass

现在我想知道,这可以 "extended" 到自定义类型吗?能否以正式的方式为自定义类型(充当容器)提供索引,以告知潜在的类型检查器内容必须属于特定类型?

比如collections.Counterclass? - 当我真的想要一个计数器时,上述约束将不起作用,因为字典不提供加法运算符,而计数器提供。

我可以这样做:

def myFun(inputDict:collections.Counter): pass

但后来我失去了柜台存储的信息。 - 这里使用 TypeVar 是正确的方法吗?

CounterTy = typing.TypeVar("CounterTy", collections.Counter)
def myFun(inputDict:CounterTy[str]): pass

我不清楚 Typevar 是否应该以这种方式工作。编辑:为了清楚起见,上面的代码不起作用并且 TypeVar 行出现错误。

如果您正在编写自己的容器类型并希望以与 typing.Dict 和其他类型相同的方式对其进行参数化,则应使用 typing.Generic 作为您的基础之一(使用 TypeVar 作为其参数):

from typing import TypeVar, Generic, Iterable

T = TypeVar('T')

class MyContainer(Generic[T]):
    def __init__(self, iterable:Iterable[T]):
        ...

    def foo(self) -> T:
        ...

def some_function(arg: MyContainer[str]) -> str:
    return arg.foo()