7

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

Shengxin Huang
  • 647
  • 1
  • 11
  • 25
  • Actually that produces a ModuleNotFoundError... Fixing that, you only see a TypeError if you're using Python <3.9, in which case you need the typing version not the abc version: https://docs.python.org/3/library/typing.html#typing.Sequence – jonrsharpe Feb 11 '22 at 09:09
  • Does this answer your question? [Type hinting a collection of a specified type](https://stackoverflow.com/questions/24853923/type-hinting-a-collection-of-a-specified-type) – MisterMiyagi Feb 11 '22 at 09:24
  • 1
    TLDR: If you are using a Python version before 3.9 you must use the corresponding generic from ``typing``. – MisterMiyagi Feb 11 '22 at 09:25

1 Answers1

2

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

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
Davide Laghi
  • 116
  • 1
  • 5