List[Optional[int]] 分配时的类型检查

List[Optional[int]] type checking when assigning

mypy 似乎足够聪明,可以在检查 None 的可选值后检测到类型的 Optional 部分被忽略了。

含义:声明值:Optional[int] 会导致值在 if value is not None.

之后表现得像 int

我想我遇到了类似的问题,但是 Optional intlist 中。

这是演示片段

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] is not None 但我不知道为什么它仍然无法将 a[0] 的类型从 int | None 缩小到 int 作为条件None 已被选中。

我相信 mypy 目前理解 is Noneis not None 检查:

https://github.com/python/mypy/issues/8000

You need to do if self.ignore is None for mypy to pick up that [...]

很显然

if a[0] is not None:

应该可以。请注意 is not None!= None may not mean the same thing 无论如何。