This exercise is extracted from the book Python Object-Oriented Programming
In Python, we can use different types of collections to store data. The most common ones are lists, tuples, sets, and dictionaries.
All these built-in collections implement the Collection
protocol, which acts as an abstraction for the different types of collections.
The Collection
at the same time depends on the Container
, Iterable
, and Sized
protocols.
Container
- It defines the
__contains__
method, which is used to check if a collection contains a specific element. - By implementing the
__contains__
method, a collection can be used in thein
andnot
operators.
Iterable
- It defines the
__iter__
method, which is used to iterate over the elements of a collection. - By implementing the
__iter__
method, a collection can be used in afor
loop.
Sized
- It defines the
__len__
method, which is used to get the number of elements in a collection. - By implementing the
__len__
method, a collection can be used in thelen
function.
The class diagram of the built-in dictionary is shown below.
Important
In the explanation of the commits section we will understand why this class hierarchy is important.
Note
All these class definitions can be found inside typing.pyi and builtins.pyi files.
In Python, we can create a dictionary in two ways using the overload decorator:
-
Passing a sequence of key-value pairs to the
dict
constructor.my_dict = dict({"a": 42, "b": 43, "c": 44})
-
Passing a list of tuples with key-value pairs to the
dict
constructor.my_dict = dict([("a", 42), ("b", 43), ("c", 44)])
We want to create a custom immutable dictionary. The goal is to be able to load our dictionary-like mapping once with its keys and values, and then use it to map the keys to their values.
We want to end up with a type hint like this:
BaseMapping = Mapping[Comparable, Any]
We are going to create a dictionary-like mapping from some key to an object of any type.
We've defined the key as Comparable
because we want to be able to compare the keys and sort them in order.
The commits of the main branch explain step by step how the process is done.