Python Pycharm静态类型检查器失败
也许有人能帮我。 我已经为这个pycharm集成的静态类型检查器奋斗了很长时间 一些规格:Python Pycharm静态类型检查器失败,python,pycharm,type-hinting,Python,Pycharm,Type Hinting,也许有人能帮我。 我已经为这个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
- Python 3.7.7
- Windows 10 Pro x64
- 专业2020.1.3
- 社区2020.2.3
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
如果您查看这一行,您将注意到没有显示任何错误
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的执行/性能中看到的问题。我还添加了一个更新的屏幕截图。Pycharm和mypy都是正确的,因为bool是从int派生的,并且通过指示您需要int,您可以接受从int派生的任何类型的变量
您可以通过执行IsubClass(bool,int)验证bool是从int派生的。在@Sylvaus的帮助下,我找到了问题所在并找到了解决方案 PyCharm不识别违反,但mypy正确地识别了! 通过安装Mypy插件 文件->设置->插件 如果您运行mypy,它将告诉您现在有错误。但是需要一段时间才能触发pycharms分析器并显示mypy的结果 我将尝试将分析器绑定到代码格式快捷方式。如果我能做到,我会更新这篇文章 编辑:
这是来自jetbrains的消息,这是否回答了您的问题?谢谢你的快速回复。我根据您的澄清更新了我的问题。事实并非如此,自2016年以来,PyCharm()支持PEP 526,在类级别上注释您的属性,所有预期的警告都将被提出。@user2235698为什么它不识别上述示例中的违规行为?为什么我应该使用类变量而不是实例变量?它不是类变量,例如:
class MyClass:integer:int
,而是类级别的注释hm。我试过了,但还是没有用PyCharm打字机发出警告。Mypy确实向我显示了警告。对不起,你是对的: