Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

typing

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.

like image 774
rozumir Avatar asked Feb 11 '21 11:02

rozumir


People also ask

How do I fix TypeError type object is not Subscriptable?

Python throws the TypeError object is not subscriptable if you use indexing with the square bracket notation on an object that is not indexable. This is the case if the object doesn't define the __getitem__() method. You can fix it by removing the indexing call or defining the __getitem__ method.

What does it mean when an object is not Subscriptable?

Python TypeError: 'int' object is not subscriptableThis error occurs when you try to use the integer type value as an array. In simple terms, this error occurs when your program has a variable that is treated as an array by your function, but actually, that variable is an integer.

How do you make an object Subscriptable in Python?

The type of 'class object' is define by __metaclass__ , default to type . So if you need a subscriptable class, just implement __getitem__ in its __metaclass__ .

Why is set in Python not Subscriptable?

The Python "TypeError: 'set' object is not subscriptable in Python" occurs when we try to access a set object at a specific index, e.g. my_set[0] . To solve the error, use square brackets to declare a list, because set objects are unordered and not subscriptable.


1 Answers

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]
like image 81
khelwood Avatar answered Sep 22 '22 23:09

khelwood