英文:
TypeVar in python
问题
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 the container could only be of type 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 the 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.
英文:
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.
答案1
得分: 1
你已将 ls
注释为 List[Any]
。Any
是 Mypy 的逃逸口,告诉它不要进行类型检查,并接受对象上的任何操作。例如,
x: Any = 3
x + "foo"
可以很好地进行类型检查。如果删除 List[Any]
提示,或将其更改为 list[object]
或 list[int | str | tuple[str]]
(Python 3.10+ 语法),则会收到错误消息,正如您所期望的那样。
此问题的答案可能会有所帮助。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论