【问题标题】:mypy: how to best deal with random.choicemypy:如何最好地处理 random.choice
【发布时间】:2020-10-03 02:22:38
【问题描述】:

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

赋值类型不兼容(表达式类型为“object”,变量类型为“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”无济于事,因为 mypy 抱怨 object 没有 mymethod 属性。

【问题讨论】:

    标签: python-3.x mypy python-typing


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2013-06-13
      • 2014-01-28
      • 2021-06-16
      • 2013-06-19
      • 1970-01-01
      • 2020-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多