James Kingston Clarke

TIL Why `TypeVar` is better over `Union` (in certain cases)

It’s better to use TypeVar over Union in cases where you want the type of a variable to remain constant across a given scope.

For example, if you wanted to pass either a str or an int to a function, and return either a str or an int from that function, you could do the following

def foo(bar: Union[str,int]) -> Union[str,int]: ...

However, you can’t guarantee that if you passed in a str you’d return a str; it could still possibly be an int. To guarantee the return type is the same as the input type, in this case bar, you can do the following

T = TypeVar("T", str, int)

def foo(bar: T) -> T: ...

or with PEP 695

def foo[T: (str, int)](bar: T) -> T: ...

References