[go: up one dir, main page]

DEV Community

Cover image for 1.Collections and ABC'S
Ashish Reddy
Ashish Reddy

Posted on

1.Collections and ABC'S

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:
  1. Iterable (i.e implementation of iter Dunder method)
  2. Sized (i.e implementation of len Dunder method)
  3. Container (i.e implementation of contains Dunder method)

There are 3 important and most useful categories in Collections API:

  1. Sequence (generalizing the built-in lists,strings in python)
  2. Mapping (dict/default dict is implemented and other methods)
  3. 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

Enter fullscreen mode Exit fullscreen mode

In the next Blog lets deep dive into Sequences

Top comments (0)