Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
528 views
in Technique[技术] by (71.8m points)

python - Example code from typing library causes TypeError: 'type' object is not subscriptable, why?

Considering to Python Docs for typing why code below isn't working?

>>> Vector = list[float]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'type' object is not subscriptable

In docs there is the same example as I mentioned above. here

Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

I didn't find question about this example.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The ability to use the [] operator on types like list for type hinting was added in 3.9.

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

In earlier versions it will generate the error you describe, and you need to import List object from typing instead.

from typing import List
List[float]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...