如何解决PyCharm 中的类型检查类静态变量
我在 PyCharm 项目中有以下 Python 代码:
class Category:
text: str
a = Category()
a.text = 1.5454654 # where is the warning?
编辑器应该显示警告,因为我正在尝试设置类型错误的属性。看看下面的设置:
解决方法
这是一个错误,PyCharm implements its own static type checker,如果您尝试 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。
顺便说一下,还值得一提的是,问题中的示例设置了一个静态类变量,但也通过在实例上设置值来重新绑定它。 This thread 给出了冗长的解释。
>>> Category.text = 11
>>> a.text = 1.5454654
>>> a.text
1.5454654
>>> Category.text
11
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。