处理以下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属性。
[ClassTwo(self.Bar), ClassThree(self.Bar)]
的类型为List[object]
,这是合理的,因为object
是ClassTwo
和ClassThree
的最后一个通用基类。