首页 > 解决方案 > mypy:使用更高(个人)类型

问题描述

我最近发现了 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的“低级类型”。

我应该如何纠正?

标签: pythonannotationsmypytype-hinting

解决方案


检查Github 问题

从那里可以看出,在官方文档中,它是按设计的

作为一种解决方法,引用JukkaL 在 github 上的评论

您可以经常使用Sequence[x]而不是List[x]让代码像您的示例一样工作。这是有效的,因为Sequence它是协变的,并且不允许您在列表中设置项目,这与List[x]它是不变的并且允许列表的突变不同。


推荐阅读