/python-custom-builtin

A custom implementation of a Python dictionary

Primary LanguagePython

Creating a custom dictionary in Python

Python

This exercise is extracted from the book Python Object-Oriented Programming

Introduction

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 the in and not 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 a for 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 the len function.

Built-in dictionary

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.

MappingAbstractions

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:

  1. Passing a sequence of key-value pairs to the dict constructor.

    my_dict = dict({"a": 42, "b": 43, "c": 44})
  2. Passing a list of tuples with key-value pairs to the dict constructor.

    my_dict = dict([("a", 42), ("b", 43), ("c", 44)])

Custom dictionary

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.

Code explanation

The commits of the main branch explain step by step how the process is done.

  1. Defining the Comparable protocol
  2. Ho to use @overload decorator to allow different signatures
  3. What means to inherit from Sized
  4. What means to inherit from Iterable
  5. What means to inherit from Container
  6. What means to inherit from Mapping

Visit my GitHub profile for more projects 🚀

Web