类型检查 class PyCharm 中的静态变量
Type checking class static variables in PyCharm
我在 PyCharm 项目中有以下 Python 代码:
class Category:
text: str
a = Category()
a.text = 1.5454654 # where is the warning?
当我尝试设置错误类型的属性时,编辑器应该会显示警告。看看下面的设置:
这是一个错误,PyCharm implements its own static type checker, if you try the same code using 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)
编辑: 在评论中指出有一个错误报告 PY-36889 on JetBrains。
另外值得一提的是,问题中的示例设置了一个静态 class 变量,但也通过在实例上设置值来重新绑定它。 This thread给出了冗长的解释。
>>> Category.text = 11
>>> a.text = 1.5454654
>>> a.text
1.5454654
>>> Category.text
11
我在 PyCharm 项目中有以下 Python 代码:
class Category:
text: str
a = Category()
a.text = 1.5454654 # where is the warning?
当我尝试设置错误类型的属性时,编辑器应该会显示警告。看看下面的设置:
这是一个错误,PyCharm implements its own static type checker, if you try the same code using 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)
编辑: 在评论中指出有一个错误报告 PY-36889 on JetBrains。
另外值得一提的是,问题中的示例设置了一个静态 class 变量,但也通过在实例上设置值来重新绑定它。 This thread给出了冗长的解释。
>>> Category.text = 11
>>> a.text = 1.5454654
>>> a.text
1.5454654
>>> Category.text
11