首页 > 解决方案 > List[Optional[int]] 分配时的类型检查

问题描述

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

含义:声明 value:Optional[int]将导致 value 的行为类似于intafter if value is not None

我想我被困在一个类似的问题上,但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] 的类型从toa[0] is not None缩小,因为已经检查了 for 的条件。int | NoneintNone

标签: pythonpython-3.xtype-hintingtypingmypy

解决方案


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

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

你需要做if self.ignore is Nonemypy是拿起那个 [...]

很明显

if a[0] is not None:

应该管用。请注意,is not None无论如何,这!= None 可能并不意味着同样的事情。


推荐阅读