Example code from typing library causes TypeError: 'type' object is not subscriptable, why?
Example code from typing library causes TypeError: 'type' object is not subscriptable, why?
正在考虑 Python typing
的文档,为什么下面的代码不起作用?
>>> Vector = list[float]
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: 'type' object is not subscriptable
在文档中有与我上面提到的相同的示例。 here
Vector = list[float]
def scale(scalar: float, vector: Vector) -> Vector:
return [scalar * num for num in vector]
我没有找到关于这个例子的问题。
在 3.9 中添加了在 list
等类型上使用 []
运算符进行类型提示的功能。
https://docs.python.org/3/whatsnew/3.9.html#type-hinting-generics-in-standard-collections
在早期版本中,它会生成您描述的错误,您需要改为从 typing
导入 List
对象。
from typing import List
List[float]
正在考虑 Python typing
的文档,为什么下面的代码不起作用?
>>> Vector = list[float]
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: 'type' object is not subscriptable
在文档中有与我上面提到的相同的示例。 here
Vector = list[float]
def scale(scalar: float, vector: Vector) -> Vector:
return [scalar * num for num in vector]
我没有找到关于这个例子的问题。
在 3.9 中添加了在 list
等类型上使用 []
运算符进行类型提示的功能。
https://docs.python.org/3/whatsnew/3.9.html#type-hinting-generics-in-standard-collections
在早期版本中,它会生成您描述的错误,您需要改为从 typing
导入 List
对象。
from typing import List
List[float]