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.
You've annotated ls
as List[Any]
. Any
is Mypy's escape hatch, that tells it not to type check, and to accept any operation on the object. For instance,
x: Any = 3
x + "foo"
type checks just fine. If you remove the List[Any]
hint, or change it list[object]
or list[int | str | tuple[str]]
(Python 3.10+ syntax), you get an error as you'd expect.
The answer to this question may be of help.