Ariksu
Ariksu

Reputation: 83

Can we use Union inside generics typehinting in python?

I am writing a function which parses a Union type object with list of parsers (with concrete types) and return a unioned type. However I found I cannot get Union working correctly with 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)

I am expecting to get Union[int,str] as a type for result, but got object instead. Is there a way to union listed types without explicitly stating those?

Upvotes: 1

Views: 3116

Answers (1)

gniourf_gniourf
gniourf_gniourf

Reputation: 46813

That's because you didn't specify test's type. The following will work:

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]'

If you don't specify test's type, mypy will infer that test's type is List[object]. If you had given:

test = [0, 1]

(even without type declaration), mypy would infer that test's type is List[int], and the revealed type of result would be int.

Upvotes: 2

Related Questions