Search code examples
pythonpython-typing

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.


Solution

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

    What's new in Python 3.9

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

    from typing import List
    List[float]