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.
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.
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.
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__ .
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With