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

问题描述 投票:0回答:1

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

分配中的不兼容类型(表达式的类型为“对象”,变量的类型为“ 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

您可以看到我正在根据条件选择一个初始化的类并在其上运行一个方法。

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

在Foo的类型声明中添加“ object”或“ Any”不能帮助cos,然后mypy抱怨对象没有mymethod属性。

python-3.x mypy python-typing
1个回答
0
投票
Mypy推断[ClassTwo(self.Bar), ClassThree(self.Bar)]的类型为List[object],这是合理的,因为objectClassTwoClassThree的最后一个通用基类。
© www.soinside.com 2019 - 2024. All rights reserved.