打字,自定义集合类型

pau*_*l23 6 python counter typing

打字模块提供了一些方便的功能,以提高可读性和对键入的代码正确性的信心。

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

def myFun(inputDict:Dict[str, int]): pass
Run Code Online (Sandbox Code Playgroud)

现在我想知道,这可以“扩展”到自定义类型吗?是否可以以正式的方式为自定义类型(其作用类似于容器)提供索引以告诉潜在的类型检查器内容必须是特定类型?

例如collections.Counter班级?- 当我真的想要一个计数器时,上面的约束将不起作用,因为字典不提供加法运算符,而计数器可以。

我可以做这样的事情:

def myFun(inputDict:collections.Counter): pass
Run Code Online (Sandbox Code Playgroud)

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

CounterTy = typing.TypeVar("CounterTy", collections.Counter)
def myFun(inputDict:CounterTy[str]): pass
Run Code Online (Sandbox Code Playgroud)

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

Blc*_*ght 6

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

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