Skip to content

Better typing hints in python?

An answer to this question on Stack Overflow.

Question

How can I be specific when I am using Union of types, let's say I have wrote a function which accepts either str or list and outputs whatever type was passed in, consider the following example

from typing import Union
def concat(x1: Union[str, list], x2: Union[str, list]) -> Union[str, list]:
    return x1 + x2

I want the above example to be more specific like x1, x2 and returned value from the function all three must match the same types, but those types must be either str or list.

Answer

from typing import TypeVar
T = TypeVar("T")
def concat(x1: T, x2: T) -> T:
    return x1 + x2