识别列表理解类型

Recognise list comprehension type

采用以下代码:

from typing import Union

value: Union[str, bytes]
stripped = [line.strip() for line in value.splitlines()]

reveal_type(stripped)

任何阅读的人,很明显 stripped 应该是

类型
Union[List[str], List[bytes]]

然而,mypy将其识别为

List[Union[str, bytes]]

如何让 mypy 将其识别为 Union[List[str], List[bytes]]

你可以试试这个:

from typing import Union

value: Union[str, bytes]
stripped_str =[]

if isinstance(value, str):
    stripped_str = [line.strip() for line in value.splitlines()]
else:
    stripped_bytes = [line.strip() for line in value.splitlines()]

stripped = stripped_str or stripped_bytes

reveal_type(stripped)

所以Mypy发现stripped的类型是Union[list[str], list[bytes]].