PyCharm 中的类型检查类静态变量

Sex*_*yMF 5 python static-variables typechecking pycharm python-typing

我在 PyCharm 项目中有以下 Python 代码:

class Category:
    text: str

a = Category()
a.text = 1.5454654  # where is the warning?
Run Code Online (Sandbox Code Playgroud)

当我尝试设置错误类型的属性时,编辑器应该显示警告。看看下面的设置:

PyCharm 设置配置的屏幕截图

bad*_*der 4

这是一个错误,PyCharm 实现了自己的静态类型检查器,如果您使用 MyPy 尝试相同的代码,静态类型检查器将发出警告。更改 IDE 配置不会改变这一点,唯一的方法是使用不同的 Linter。

我稍微修改了代码以确保文档字符串不会产生影响。

class Category:
    """Your docstring.

    Attributes:
        text(str): a description.
    """

    text: str


a = Category()

Category.text = 11  # where is the warning?
a.text = 1.5454654  # where is the warning?
Run Code Online (Sandbox Code Playgroud)

MyPy 确实给出以下警告:

main.py:13: error: Incompatible types in assignment (expression has type "int", variable has type "str")
main.py:14: error: Incompatible types in assignment (expression has type "float", variable has type "str")
Found 2 errors in 1 file (checked 1 source file)
Run Code Online (Sandbox Code Playgroud)

编辑:在评论中指出JetBrains 上有一个错误报告 PY-36889

顺便说一句,还值得一提的是,问题中的示例设置了一个静态类变量,但也通过在实例上设置值来重新绑定它。这个线程给出了很长的解释。

main.py:13: error: Incompatible types in assignment (expression has type "int", variable has type "str")
main.py:14: error: Incompatible types in assignment (expression has type "float", variable has type "str")
Found 2 errors in 1 file (checked 1 source file)
Run Code Online (Sandbox Code Playgroud)

  • 事实上,为此提交了一个错误:[PY-36889](https://youtrack.jetbrains.com/issue/PY-36889)。不过一年了还没修好。 (2认同)