In [1]:
import collections

In [2]:
def print_len_abc_sized(x):
    if isinstance(x, collections.abc.Sized):
        print(len(x))
    else:
        print('x is not Sized')

In [3]:
print_len_abc_sized([0, 1, 2])


3

In [4]:
print_len_abc_sized('abc')


3

In [5]:
print_len_abc_sized({0, 1, 2})


3

In [6]:
print_len_abc_sized(100)


x is not Sized

In [7]:
def print_len_abc_sequence(x):
    if isinstance(x, collections.abc.Sequence):
        print(len(x))
    else:
        print('x is not Sequence')

In [8]:
print_len_abc_sequence([0, 1, 2])


3

In [9]:
print_len_abc_sequence('abc')


3

In [10]:
print_len_abc_sequence({0, 1, 2})


x is not Sequence

In [11]:
print_len_abc_sequence({'k1': 1, 'k2': 2, 'k3': 3})


x is not Sequence

In [12]:
def print_len_abc_mutablesequence(x):
    if isinstance(x, collections.abc.MutableSequence):
        print(len(x))
    else:
        print('x is not MutableSequence')

In [13]:
print_len_abc_mutablesequence([0, 1, 2])


3

In [14]:
print_len_abc_mutablesequence('abc')


x is not MutableSequence

In [15]:
print_len_abc_mutablesequence((0, 1, 2))


x is not MutableSequence

In [16]:
class MySequence(collections.abc.Sequence):
    def __len__(self):
        return 10

In [17]:
# ms = MySequence()
# TypeError: Can't instantiate abstract class MySequence with abstract methods __getitem__

In [18]:
class MySequence(collections.abc.Sequence):
    def __len__(self):
        return 10
    def __getitem__(self, i):
        return i

In [19]:
ms = MySequence()

In [20]:
print(len(ms))


10

In [21]:
print(ms[3])


3

In [22]:
print(ms.index(5))


5

In [23]:
print(list(reversed(ms)))


[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

In [24]:
print(isinstance(ms, collections.abc.Sequence))


True

In [25]:
print(hasattr(ms, '__len__'))


True

In [26]:
class MySequence_bare():
    def __len__(self):
        return 10

    def __getitem__(self, i):
        return i

In [27]:
msb = MySequence_bare()

In [28]:
print(len(msb))


10

In [29]:
print(msb[3])


3

In [30]:
# print(msb.index(5))
# AttributeError: 'MySequence_bare' object has no attribute 'index'

In [31]:
print(isinstance(msb, collections.abc.Sequence))


False

In [32]:
print(hasattr(msb, '__len__'))


True