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

Mypy: use higher (personal) type

我最近发现了 mypy,我希望用它对我的代码进行类型检查。

我有一个 Something 基地 class:

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

我有几个子class,它们都是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 识别为 "lower types" 的 Something。

我该如何纠正?

勾选Github issue

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

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

You can often use Sequence[x] instead of List[x] to get code like your example working. This works because Sequence is covariant and doesn't let you set items in the list, unlike List[x] which is invariant and allows the mutation of the list.