Question
What's the difference between a constrained TypeVar and a Union?
If I want to have a type that can be multiple possible types, Union
s seem to be how I represent that:
U = Union[int, str]
U
can be an int
or a str
.
I noticed though that TypeVar
s allow for optional var-arg arguments that also seem to do the same thing:
T = TypeVar("T", int, str)
Both T
and U
seem to only be allowed to take on the types str
and int
.
What are the differences between these two ways, and when should each be preferred?