Difference between constrained 'TypeVar' and 'Union' in Python

Redowan Delowar January 19, 2022
Source
If you want to define a variable that can accept values of multiple possible types, using typing.Union is one way of doing that: However, there's another way you can express a similar concept via constrained TypeVar. You'd do so as follows: So, what's the difference between these two and when to use which? The primary difference is: > T's type needs to be consistent across multiple uses within a given scope, while U's > doesn't. With a Union type used as function parameters, the arguments, as well as the return type, can all be different: However, the above type definition will be too loose if you need to ensure that all of your function parameters must be of the same type in a single scope. Here's where constrained TypeVar can come in handy: If you run Mypy against the above snippet, you'll get this: As the comment implies, this error is coming from the line where I called add("hello", 1). The function add can take parameters of either integer or string type. However, the type of both the parameters needs to be the same. Also, the type of the input parameters will define the type of the output value. So, the types of the input parameters must match, otherwise, Mypy will complain and in this case, the snippet will also raise a TypeError in runtime. Mypy is statically catching a bug that'd otherwise appear in runtime, how convenient! Further reading - [What's the difference between a constrained TypeVar and a Union?] [what's the difference between a constrained typevar and a union?]: https://stackoverflow.com/questions/58903906/whats-the-difference-between-a-constrained-typevar-and-a-union

Discussion in the ATmosphere

Loading comments...