我们可以在python中使用泛型内部的Union类型提示吗?

2024-09-30 16:22:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个函数,它用解析器列表(具有具体类型)解析Union类型对象并返回unioned类型。但是我发现我不能让Union和List generic一起正常工作。在

from typing import List,Union,TypeVar
T=TypeVar("T")
T1=TypeVar("T1")

def union_list(l: List[Union[T,T1]] )-> Union[T,T1]:
    return l[0]

test=[0,"_"]
result=union_list(test)
reveal_type(result)

我希望得到Union[int,str]作为result的类型,但得到的却是object。有没有一种方法可以不显式地联合列出的类型?在


Tags: 对象函数test解析器类型列表resultgeneric
1条回答
网友
1楼 · 发布于 2024-09-30 16:22:19

这是因为您没有指定test的类型。以下将起作用:

from typing import List, TypeVar, Union

T = TypeVar("T")
T1 = TypeVar("T1")


def union_list(l: List[Union[T, T1]])-> Union[T, T1]:
    return l[0]


# Here, specify the type of test
test = [0, "_"]  # type: List[Union[int, str]]
result = union_list(test)
reveal_type(result)
# Happily answers: Revealed type is 'Union[builtins.int, builtins.str]'

如果不指定test的类型,mypy将推断test的类型是List[object]。如果你给了:

^{pr2}$

(即使没有类型声明),mypy会推断出test的类型是List[int],而{}显示的类型将是{}。在

相关问题 更多 >