Python + mypy + mixin = 没有属性错误

ype*_*kov 5 python mixins visual-studio-code mypy

我在 UI 界面中出现 Vscode + mypy 错误:“EngineMixin”没有下一个 Mixin 类的属性“engine”

class EngineMixin:
    def prepare_start(self):
        self.engine.start()

    def prepare_stop(self):
        self.engine.stop()

    def __str__(self):
        output = super().__str__()
        output += f'\n{self.__class__.__name__} characteristics. Engine [{self.engine}]' # noqa
        return output
Run Code Online (Sandbox Code Playgroud)

事实上,这个错误仅在Vscode UI界面中显示。当我在 cli 中运行 mypy 时,没有错误。总的来说,我明白为什么会出现这个错误,但是有什么方法可以在 vscode 中抑制它吗?

编辑(添加屏幕): 截屏

Oli*_*ice 13

对于引用它们要混合到的类的 mixin,您可以使用类型存根让 mypy 知道self.engine预期存在

class EngineMixin:

    # Like this
    engine: Engine

    def prepare_start(self):
        self.engine.start()

    def prepare_stop(self):
        self.engine.stop()

    def __str__(self):
        output = super().__str__()
        output += f'\n{self.__class__.__name__} characteristics. Engine [{self.engine}]' # noqa
        return output
Run Code Online (Sandbox Code Playgroud)