Source From Here
My function needs to accept an object, from which data can be extracted by index, viz. a List or an instance with defined __getitem__ method.
Which type can I use for type hinting this argument?
There are several different ways you can do this.
If you're ok with using only custom classes (that you can write) as indexable containers:
The issue is, of course, that if you wanted to pass in a plain old list into the function, you wouldn't be able to do so since list doesn't subclass your custom type.
We could maybe special-case certain inputs via clever use of the @overload decorator and unions, but there's a second, albeit experimental, way of doing this known as Protocols.
Protocols basically let you express "duck typing" in a sane way using type hints: the basic idea is that we can tweak IndexableContainer to become a protocol. Now, any object that implements the __getitem__ method with the appropriate signature is counted as a valid IndexableContainer, whether or not they subclass that type or not.
The only caveat is that Protocols are currently experimental and (afaik) only supported by mypy. The plan is to eventually add protocols to the general Python ecosystem -- see PEP 544 for the specific proposal -- but I haven't kept track of the discussion/don't know what the status of that is.
In any case, to use protocols, install the typing_extensions module using pip. Then, you can do the following: