键入库中的示例代码导致 TypeError: 'type' object is not subscriptable,为什么?

时间:2021-02-11 11:37:57

标签: python typing

考虑使用 Python Docs for 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]

我没有发现有关此示例的问题。

1 个答案:

答案 0 :(得分:9)

在 3.9 中添加了在 [] 等类型上使用 list 运算符进行类型提示的功能。

https://docs.python.org/3/whatsnew/3.9.html#type-hinting-generics-in-standard-collections

在早期版本中,它会生成您描述的错误,您需要从 List 导入 typing 对象。

from typing import List
List[float]