I ran the following code in Jupyter Notebook:
%load_ext nb_mypy
from typing import Any, List, Union, TypeVar
T = TypeVar("T",int,str)
def first(container: List[T]) -> T:
return container[2]
ls: List[Any] = [1,"hello",("hello",)]
first(ls)
And the result was:
('hello',)
Here, I constrained the variable T
to represent only str
or int
types. Then, I constrained the container
parameter of the function. I believed that the elements in container could only be int or str, but when I tried to pass a list ls
containing tuples, mypy did not report an error. I cannot understand why.
Doesn't List[T]
mean that container can only contain variables of type T
? Here, I also constrained the return value of the function to be of type T
, but it seems to have had no effect, as the function still returned a tuple, and mypy did not report any errors.