我正在编写一个函数,它用解析器列表(具有具体类型)解析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。有没有一种方法可以不显式地联合列出的类型?在
这是因为您没有指定
test
的类型。以下将起作用:如果不指定
^{pr2}$test
的类型,mypy将推断test
的类型是List[object]
。如果你给了:(即使没有类型声明),mypy会推断出}显示的类型将是{}。在
test
的类型是List[int]
,而{相关问题 更多 >
编程相关推荐