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: ...