mypy 类型和可选过滤

mypy types and optional filtering

我是 mypy 的新手,在从集合中过滤可选值时,我无法找到使类型正常工作的正确方法。

from typing import Optional, List

list1: List[Optional[int]] = [1, None, 3]
# This type is an error, filter can't even handle a list with optionals
list2: List[int] = list(filter(lambda n: n is not None, list1))

我应该投这个吗? mypy 是否应该能够推断 None 现在被过滤掉了?

使用 typing.cast 应该可行,但我认为这里最好的解决方案是使用列表理解。

以下代码为我传递 mypy:

from typing import Optional, List

list1: List[Optional[int]] = [1, None, 3]
list2: List[int] = [x for x in list1 if x is not None]

一般来说,列表推导式是表达 mapping/filtering 操作的更惯用的方式。 (Guido 实际上想删除 Python 3 中的 map/filter!)