mypy:如何忽略 mixin 中的“缺少属性”错误

kur*_*tgn 5 mypy

我无法让 mypy 与 mixin 一起正常工作:它一直抱怨我的 mixins 引用了缺少的属性。考虑这个例子:

class PrintValueMixin:
    """A mixin that displays values"""

    def print_value(self) -> None:
        print(self.value)


class Obj(PrintValueMixin):
    """An object that stores values. It needs a mixin to display its values"""

    def __init__(self, value):
        self.value = value


instance = Obj(1)
instance.print_value()
Run Code Online (Sandbox Code Playgroud)

如果我在这个文件上运行 mypy,我会收到一个错误:

error: "PrintValueMixin" has no attribute "value"
Run Code Online (Sandbox Code Playgroud)

当然它没有属性“值”。它是一个mixin,它不应该有自己的属性!

那么我如何让 mypy 理解这一点呢?

paw*_*cki 5

我认为这是一个设计不完善的类层次结构的标志。Mixins 不应该依赖于继承它们的类中的东西。我知道这是反对鸭子类型的,但我们处于“静态”类型领域,这里的规则更加严格。

如果你想在不重构代码的情况下摆脱这个问题,你可以执行以下操作:

class PrintValueMixin:
    """A mixin that displays values"""
    value: int   # or whatever type it has

    def print_value(self) -> None:
        print(self.value)                                
Run Code Online (Sandbox Code Playgroud)

现在,错误消失了。这是因为 mypy 将其value视为类属性。注意它是未初始化的——value没有任何对象绑定到它。因此,这在运行时没有实际影响,您不会错误地使用它。