【问题标题】:Typing, custom collection type打字,自定义集合类型
【发布时间】:2017-03-22 17:21:53
【问题描述】:

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

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

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

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

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

我可以这样做:

def myFun(inputDict:collections.Counter): pass

但是我失去了关于柜台存储什么的信息。 - 在这里使用TypeVar 是正确的方法吗?

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

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

【问题讨论】:

  • 如果您尝试实现自己的类型,听起来您正在寻找typing.Generic。不幸的是,collections.Counter 根本没有类型提示,因此您不能使用该语法。
  • @Blckknght 谢谢,但这让我很困惑,我试过typing.Generic[str] - 但返回“TypeError: Initial parameters must be type variables; got

标签: python counter typing


【解决方案1】:

如果您正在编写自己的容器类型并希望以与 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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-21
    • 2018-07-17
    相关资源
    最近更新 更多