也许有人能帮我。我已经努力了很长一段时间,与这个静态类型检查器,吡喃集成。
一些规格:
我尝试了下面的PyCharm版本。
我试图说明这个问题。您可以将其复制并粘贴到您的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如果您查看这一行,您将注意到没有显示错误。
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那么,谁能告诉我为什么setter的类型检查工作正常,而其他的任务却不能呢?
到目前为止,我一直使用getter/setter来验证是否将为彼此分配正确的类型。因此,我用'__‘标记私有字段,这样没有人可以直接更改状态。因为我已经从python3.5.x更新到3.7.x,所以我认为我可以删除这个样板代码。我希望具有静态类型检查功能,但我不想一直强迫自己使用getter/setter。
谢谢你的帮助。
诚挚的问候
更新18.11.2020: 12:00对不起误导的例子。我已经试着编辑剪辑,希望这个问题现在是明确的。我还试图更详细地解释一下,在这个执行/执行过程中我看到了什么问题。我还添加了一个更新的截图。
发布于 2020-11-20 13:33:44
在@Sylvaus的帮助下,我找出了问题所在,并找到了解决办法。
PyCharm不承认违反佩普-526,但是mypy是正确的!安装Mypy插件
文件->设置->插件
如果你运行类型,它会告诉你,现在有错误。但是需要一段时间才能触发pycharms分析器并显示出记忆的结果。
我将尝试将分析器绑定到代码格式快捷方式。如果我能做到的话,我会更新这篇文章。
编辑:感谢user2235698这里是jetbrains https://youtrack.jetbrains.com/issue/PY-36889的问题
发布于 2020-11-16 23:34:58
Pycharm和mypy都是正确的,因为bool是从int派生的,通过指示您想要int,您可以接受任何类型从int派生的变量。
您可以通过执行issubclass(bool, int)验证bool是从int派生的。
https://stackoverflow.com/questions/64867143
复制相似问题