Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: 'ABCMeta' object is not subscriptable

Tags:

python-3.x

Here is my code:

from collecionts.abc import Sequence
from typing import TypeVar

T = TypeVar('T')
def first(a: Sequence[T]) -> T:
    return a[0]

In my understanding, I can pass any Sequence-like object as parameter into first function, like:

first([1,2,3])

and it returns 1

However, it raises a TypeError:' ABCMeta' object is not subscriptable. What is going on here? How can I make it work that I have a function using typing module which can take first element whatever its type?

UPDATE

If I use from typing import Sequence,it runs alright,what is the difference between from collections.abc import Sequence and from typing import Sequence

like image 640
Shengxin Huang Avatar asked Jul 01 '26 13:07

Shengxin Huang


1 Answers

two things.

The first one is that the typing module will not raise errors at runtime if you pass arguments that do not respect the type you indicated. Typing module helps for general clarity and for intellisense or stuff like that.

Regarding the error that you encounter is probably beacuse of the python version you are using. Try to upgrade to python >= 3.9

like image 86
Davide Laghi Avatar answered Jul 04 '26 08:07

Davide Laghi