mypy:如何最好地处理 random.choice

mypy: how to best deal with random.choice

处理以下 mypy 错误的最佳方法是什么 -

Incompatible types in assignment (expression has type "object", variable has type "Union[ClassOne, ClassTwo, ClassThree, ClassFour]")

对于以下循环:

def func(self) -> List:
        thing = [x for x in self.Bar if x.condition]
        Foo: Union[ClassOne, ClassTwo, ClassThree, ClassFour]
        if len(thing) == 1:
            Foo = ClassOne(self.Bar)
        elif len(thing) == 2:
            Foo = random.choice([ClassTwo(self.Bar), ClassThree(self.Bar)])
        elif len(thing) == 3:
            Foo = ClassFour(self.Bar)
        result = Foo.mymethod()

        return result

如您所见,我选择了一个基于条件的初始化 class 和 运行 方法。

当使用 random.choice 时,mypy 坚持类型是对象。

在 Foo 的类型声明中添加 "object" 或 "Any" 没有帮助,因为 mypy 抱怨对象没有 mymethod 属性。

Mypy 推断 [ClassTwo(self.Bar), ClassThree(self.Bar)] 的类型是 List[object],这是合理的,因为 objectClassTwo 和 class 的最后一个公共基 class =15=].

但是您可以通过显式设置其类型来使其类型更具限制性:

choices: List[Union[ClassTwo, ClassThree]] = [ClassTwo(self.Bar), ClassThree(self.Bar)]
Foo = random.choice(choices)