Skip to content

1 - Union vs TypeVar

On the left, the imaginary example program would crash on the lines 8 and 9. Mypy could not help with it. On the right, mypy would complain about the lines 8 and 9, which is probably what we want. So, TypeVar is a better choice if the type must be consistent across multiple uses within a given scope.

Union vs TypeVar

Read more
The code

Left:

from typing import Union

U = Union[int, str]


def max_1(var1: U, var2: U) -> U:
    return max(var1, var2)


max_1("foo", 1)
max_1(1, "foo")
max_1("foo", "bar")
max_1(1, 2)
Right:
from typing import TypeVar

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


def max_2(var1: T, var2: T) -> T:
    return max(var1, var2)


max_2("foo", 1)
max_2(1, "foo")
max_2("foo", "bar")
max_2(1, 2)