Python 3.5 introduced type hints which allow one to write the following:
from typing import Union
answer: Union[int, str] = 42
answer = '42'
documentation: https://docs.python.org/3/library/typing.html#typing.Union
I think I understand the naive meaning of the above code. In particular, it means that the variable answer
has been given a type hint, which says that it is supposed to be of the Union
type with type parameters int
and str
, which in turn means that it is supposed to be either int
or str
.
What I do not understand, however, are the formal Python language rules around defining and using classes with type parameters in square brackets.
Can someone explain it?
Like any other use of square brackets, Union[int, str]
is implemented by Union.__getitem__((int, str))
. In this case, Union
is an instance of the class _Union
which defines __getitem__
. You don't really need to know those details to use the class.