首页 > 解决方案 > PyCharm 中的类型检查类静态变量

问题描述

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

class Category:
    text: str

a = Category()
a.text = 1.5454654  # where is the warning?

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

PyCharm 设置配置截图

标签: pythonpycharmstatic-variablestypecheckingpython-typing

解决方案


这是一个错误,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?

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)

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

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

>>> Category.text = 11
>>> a.text = 1.5454654  
>>> a.text
1.5454654
>>> Category.text
11

推荐阅读