【问题标题】:Python + mypy + mixin = has no attribute errorPython + mypy + mixin = 没有属性错误
【发布时间】:2021-01-03 16:22:08
【问题描述】:

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

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

其实这个错误只出现在Vscode UI界面。当我在 cli 中运行 mypy 时,没有错误。 总的来说,我理解为什么会出现这个错误,但是有没有办法在 vscode 中抑制它?

已编辑(添加屏幕):

【问题讨论】:

  • 欢迎来到 Stack Overflow。您认为为什么会出现此错误?为什么只在 VSCode 中?这段代码指的是什么?
  • 嗨@Steve,据我所知,mypy 插件在这个类中没有看到这个属性的声明,并说“没有属性”。这听起来合乎逻辑。但我很困惑为什么它只在 Vscode 中。 - 终端中的 mypy 本身不会出现此错误 - Pycharm 也保持沉默。我意识到,Pychaem 是我更“聪明”的。所以如果 Vscode 没问题,我也很好。但也许有办法抑制它
  • 这就是你的全部代码吗?我将它复制并粘贴到我的 .py 文件中,效果很好,没有这样的警告。我正在使用python3.9,语言服务器是Pylance。你能发布完整的截图,包括 VS Code 中的代码和错误吗?
  • 嗨@MollyWang,是的,这就是所有的代码。我已经编辑了问题并添加了屏幕截图。
  • 尝试在新的工作空间中运行此代码。

标签: python visual-studio-code mixins mypy


【解决方案1】:

对于引用它们要混入的类的 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-19
    • 2021-03-02
    • 1970-01-01
    • 2014-05-14
    • 1970-01-01
    • 2023-02-01
    • 2014-04-11
    • 2014-07-08
    相关资源
    最近更新 更多