Search⌘ K
AI Features

The ABCs of Collections

Explore the role of abstract base classes in Python's collections module. Understand how classes like Container work, how the __contains__ method supports the in operator, and discover duck typing advantages. Gain insight into creating compatible custom collections and operator overloading.

A really comprehensive use of the abstract base classes in the Python standard library lives in the collections module. The collections we use are extensions of the Collection abstract class. Collection is an extension of an even more fundamental abstraction, Container.

Since the foundation is the Container class, let’s inspect it in the Python interpreter to see what methods this class requires:

Python 3.10.4
from collections.abc import Container
print(Container.__abstractmethods__)

So, the Container class has exactly one abstract method that needs to be implemented, __contains__(). We can issue help(Container.__contains__) to see what the function signature should look ...