Typehints for Sized Iterable in Python

Solution 1:

Starting from Python3.6 there's a new type called Collection. See here.

Solution 2:

In the future Protocols will be introduced. They are already available through typing_extensions. See also PEP 544. Using Protocol the code above would be:

from typing_extensions import Protocol


class SizedIterable(Protocol):

    def __len__(self):
        pass

    def __iter__(self):
        pass


def foo(some_thing: SizedIterable):
    print(len(some_thing))
    for part in some_thing:
        print(part)


foo(['a', 'b', 'c'])

mypy takes that code without complaining. But PyCharm is saying

Expected type 'SizedIterable', got 'List[str]'

about the last line.