Python Containers
What Is a Container?
A container is any Python object that can tell you if it contains a specific item, using the in
and not in
operators. The most common containers are lists, tuples, sets, dictionaries, and strings.
In Python, the collections.abc.Container
abstract base class (ABC) defines the minimal interface for container types: the presence of the __contains__()
method.
The contains Method
To be recognized as a container, a class must implement the __contains__(self, item)
method. This method is called when you use the in
or not in
operators:
class MyContainer:
def __contains__(self, item):
return item == 42
c = MyContainer()
print(42 in c) # True
print(7 in c) # False
Using collections.abc.Container
You can check if a class or object is a container using isinstance
or issubclass
:
from collections.abc import Container
print(isinstance([1, 2, 3], Container)) # True (list is a container)
print(isinstance(42, Container)) # False (int is not a container)
You can also create your own container classes by inheriting from Container
:
from collections.abc import Container
class OnlyEven(Container):
def __contains__(self, item):
return isinstance(item, int) and item % 2 == 0
evens = OnlyEven()
print(4 in evens) # True
print(5 in evens) # False
Why Use Container?
- To make your custom classes compatible with
in
andnot in
. - To use type checking and static analysis tools that recognize the Container ABC.
- To clarify intent in your code and documentation.
Summary
collections.abc.Container
is the base class for objects supportingin
andnot in
.- Requires only the
__contains__()
method. - Used for type checking and to build custom container types.