python - PyCharm 中的类型检查类静态变量
问题描述
我在 PyCharm 项目中有以下 Python 代码:
class Category:
text: str
a = Category()
a.text = 1.5454654 # where is the warning?
当我尝试设置错误类型的属性时,编辑器应该显示警告。看看下面的设置:
解决方案
这是一个错误,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
推荐阅读
- amazon-ec2 - 当客户端不在本地主机上时,redirect_uri Keycloak 无效
- postgresql - 小更新导致挂起问题
- javascript - 使用 setTimeout 连续异步/等待
- postgresql - 使用内部连接对批量更新进行续集
- java - 带有 Web 套接字的 Spring Boot 微服务:由于缺少 EmbeddedServletContainerFactory bean,无法启动 EmbeddedWebApplicationContext
- .net - core 2.1 webapi 并发删除
- ionic-framework - 最适合链接输入或插件的离子组件
- c# - Bot接收重复的卡片点击事件
- python - 在 Azure 上获取应用程序错误我没有在本地获取
- jquery - 如何将 JavaScript 和 jQuery 更改为 Angular 4