python - List[Optional[int]] 分配时的类型检查
问题描述
mypy
似乎足够聪明,可以在检查类型部分的可选值后检测到None
被忽略。Optional
含义:声明 value:Optional[int]
将导致 value 的行为类似于int
after if value is not None
。
我想我被困在一个类似的问题上,但Optional int
在list
.
这是演示片段:
a: List[Optional[int]] = [None, None]
a[0] = 5
a[1] = 10
b: int = 0
if a[0] != None:
b = a[0]
它显示一个错误:
test.py:12: error: Incompatible types in assignment (expression has
type "Optional[int]", variable has type "int")
Found 1 error in 1 file (checked 1 source file)
我确实检查了是否,但我不知道为什么它仍然无法将 a[0] 的类型从toa[0] is not None
缩小,因为已经检查了 for 的条件。int | None
int
None
解决方案
我相信mypy
目前了解is None
并is not None
检查:
https://github.com/python/mypy/issues/8000
你需要做
if self.ignore is None
的mypy
是拿起那个 [...]
很明显
if a[0] is not None:
应该管用。请注意,is not None
无论如何,这!= None
可能并不意味着同样的事情。
推荐阅读
- python - 评估线性搜索执行速度
- r - 创建一个使用字符串和作为变量调用列的函数 - 使用基本 R 和 dplyr
- c++ - C++ 并发队列内存泄漏
- apache - Apache 反向代理中的 Google OAuth 重定向 Uri
- python - 使用python解析Javascript页面
- matlab - 为什么我在 GitHub 上的一个代码预览看起来像纯文本?
- css - Google Webfonts 破坏 CLS 分数 (FOUT)
- python - 如何在python中检查模型对象是否是Xgboost
- c# - 使用预处理器指令(符号/常量)生成docfx
- node.js - 创建 404 路由使我的所有页面都没有样式