在带有 mypy 的 TypeGuard 函数中使用泛型类型

问题描述

我有一个函数来检查列表是否包含 None,我想用它来缩小输入变量的类型:

from typing import List,Optional,TypeVar
from typing_extensions import TypeGuard

_ListElementsType = TypeVar("_ListElementsType")


def sequence_not_contains_none(maybe_optional_list: List[Optional[_ListElementsType]]) -> TypeGuard[List[_ListElementsType]]:
    return not (None in maybe_optional_list)

当此函数与输入 List[Optional[int]] 一起使用时:

integer_list: List[Optional[int]] = [10,11,12]
reveal_type(integer_list)
if int_sequence_not_contains_none(integer_list):
    reveal_type(integer_list)

我得到了错误的返回类型:

note: Revealed type is "builtins.list[Union[builtins.int,None]]"
note: Revealed type is "builtins.list[_ListElementsType`-1]"

我原以为第二种类型是 List[int]

如果我用固定的 int 切换泛型类型,它会起作用。据我了解 PEP 647 还应该支持使用泛型的版本。使用的 mypy 版本是 mypy 0.910 (python 3.8.10)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)