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
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
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