Collections: A built-in module in python standard library that helps us to create a specialized containers that go beyond built in ones(list,tuples etc).
ABC: ABC means Abstract Base Class which helps in defining interfaces in python for collections.
- collections is a also a ABC that must extends three important interfaces:
- Iterable (i.e implementation of iter Dunder method)
- Sized (i.e implementation of len Dunder method)
- Container (i.e implementation of contains Dunder method)
There are 3 important and most useful categories in Collections API:
- Sequence (generalizing the built-in lists,strings in python)
- Mapping (dict/default dict is implemented and other methods)
- Sets (Interface for sets and include various methods)
Sequence is the only one which also implements the reverse Dunder method (reverse)
Note: To create a custom container you need not to inherit (become child) of one of the class instead simply implement the specialized Dunder methods required...
Virtual subclassing: Python internally registered containers like(arrays,etc) except built-in's under different categories of ABC's (one can verify this by using isInstance and isSubclass methods of python)
The below code will work for python version >3.7 (for <=3.6 it array was not added recognized as subclass)
from array import array
from collections.abc import Sequence
arr=array('i',[7,8,9,10])
lst=[1,2,3,4,5]
print(isinstance(arr, Sequence)) # ✅ True — behaves like a Sequence
print(issubclass(array, Sequence)) # ✅ True — declared as subclass
print(isinstance(lst, Sequence)) # ✅ True — behaves like a Sequence
print(issubclass(list, Sequence)) # ✅ True — declared as subclass
In the next Blog lets deep dive into Sequences
Top comments (0)