Mypy:使用高级(个人)类型

时间:2018-07-05 13:18:17

标签: python annotations mypy typehints

我最近发现了mypy,并且希望对其进行类型检查。

我有一个Something基类:

class Something():
    ... something...

我有几个子类,它们都是Something的实例,但是类型不同:

class Thing(Something)
    def __init__():
        short_name = "S"


class OtherThing(Something)
    def __init__():
        short_name = "T"

使用这些对象时,通常将它们放在列表中:

s1 = Thing()
s2 = OtherThing()
list_things: List[Something] = list()
list_things.append(s1)
list_things.append(s2)

但是显然我做不到,mypy不能将Thing和OtherThing识别为Something的“较低类型”。

我该如何纠正?

1 个答案:

答案 0 :(得分:1)

选中Github issue

在那里可以看到,in the official docs是设计好的

作为解决方法,引用JukkaL's comment on github

  

您经常可以使用Sequence[x]而不是List[x]来获得示例工作所需的代码。之所以有效,是因为Sequence是协变的,不允许您设置列表中的项目,而List[x]则是不变的,并且允许列表的突变。