TypeVar在Python中是一个类型提示工具,用于定义通用类型变量。

huangapple go评论63阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年5月6日 19:06:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76188527.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定