Pycharm静态类型检查器失败

2024-09-29 19:35:58 发布

您现在位置:Python中文网/ 问答频道 /正文

也许有人能帮我。 我已经为这个pycharm集成的静态类型检查器奋斗了很长时间

一些规格:

  • Python 3.7.7
  • Windows 10 Pro x64

我试过以下版本

  • 专业2020.1.3
  • 社区2020.2.3

我试图说明这个问题。你可以复制&;将其粘贴到PyCharm中以验证问题

class SpecificCLS:
    pass


class CLS:
    def __init__(self):
        self.integer: int = 0
        self.specific_cls: SpecificCLS = SpecificCLS()

    def set_im_int(self, value: int):
        self.integer = value

    def get_im_int(self) -> int:
        return self.integer

    def get_specific_cls(self) -> SpecificCLS:
        return self.specific_cls

    def set_specific_cls(self, value: SpecificCLS):
        self.specific_cls = value


cls = CLS()

# Example for assigning a class into an integer
cls.integer = SpecificCLS()  # PyCharm does NOT show any error/warning that a class is assigned into an variable that is declared as an "int"
cls.set_im_int(SpecificCLS())  # PyCharm recognise an error (underlined red): Expected type 'int', got 'SpecificCLS' instead

# Example for assigning an integer into a class
cls.specific_cls = 1  # PyCharm does NOT show any error/warning that a class is assigned into an variable that is declared as an "int"
cls.set_specific_cls(1)  # PyCharm recognise an error (underlined red): Expected type 'SpecificCLS', got 'int' instead

PyCharm Screenshot

如果您查看这一行,您将注意到没有显示任何错误

cls.integer = SpecificCLS()  # PyCharm does NOT show any error/warning that a class is assigned into an variable that is declared as an "int"

如果我们使用setter方法来分配值,pycharm就是正确识别错误的分配

cls.set_im_int(SpecificCLS())  # PyCharm recognise an error (underlined red): Expected type 'int', got 'SpecificCLS' instead

那么,有谁能告诉我为什么setter的类型检查工作得很好,而其他任务却不行

到目前为止,我一直使用getter/setter来验证是否将正确的类型分配给彼此。因此,我将字段标记为private,以便没有人可以直接更改状态。 因为我已经从Python3.5.x更新到了3.7.x,所以我认为我可以删除这个样板代码。我希望有静态类型检查功能,但我不想强迫我一直使用getter/setter

我感谢你的帮助

致意

2020年11月18日更新:12:00 对不起,这个误导性的例子。我试着编辑剪报,希望问题现在清楚了。我还试图更详细地解释我在pycharm的执行/性能中看到的问题。我还添加了一个更新的屏幕截图


Tags: selfanthatisdeferrorintegerclass
2条回答

Pycharm和mypy都是正确的,因为bool是从int派生的,并且通过指示您想要一个int,您可以接受从int派生的任何类型的变量

您可以通过执行issubclass(bool, int)来验证bool是从int派生的

在@Sylvaus的帮助下,我找出了问题所在,并找到了解决方案

PyCharm不识别对PEP-526的违反,但mypy正确地识别了它! 通过安装Mypy插件

文件->;设置->;插件

如果您运行mypy,它将告诉您现在有错误。但是需要一段时间才能触发pycharms分析器并显示mypy的结果

我将尝试将分析器绑定到代码格式快捷方式。如果我能做到,我会更新这篇文章

编辑: 多亏了user2235698这是jetbrains https://youtrack.jetbrains.com/issue/PY-36889issue

相关问题 更多 >

    热门问题