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])
In [4]:
print_len_abc_sized('abc')
In [5]:
print_len_abc_sized({0, 1, 2})
In [6]:
print_len_abc_sized(100)
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])
In [9]:
print_len_abc_sequence('abc')
In [10]:
print_len_abc_sequence({0, 1, 2})
In [11]:
print_len_abc_sequence({'k1': 1, 'k2': 2, 'k3': 3})
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])
In [14]:
print_len_abc_mutablesequence('abc')
In [15]:
print_len_abc_mutablesequence((0, 1, 2))
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))
In [21]:
print(ms[3])
In [22]:
print(ms.index(5))
In [23]:
print(list(reversed(ms)))
In [24]:
print(isinstance(ms, collections.abc.Sequence))
In [25]:
print(hasattr(ms, '__len__'))
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))
In [29]:
print(msb[3])
In [30]:
# print(msb.index(5))
# AttributeError: 'MySequence_bare' object has no attribute 'index'
In [31]:
print(isinstance(msb, collections.abc.Sequence))
In [32]:
print(hasattr(msb, '__len__'))