DEV Community

Victor Silva
Victor Silva

Posted on • Updated on

Make simple Python types rich

In the previous post of this series, I created a fictional example that uses a dict to map the installments of a loan to their corresponding due dates, in the following structure:

Suppose that we pass that dict all over the place in our code, and that in some places we need to calculate the difference between the first and the last due date.
We could create a function that makes the calculation, and use it wherever we need it, right? And we could be nice to the callers by providing helpful type hints, of course:

But now we have to import that function in every place we deal with the dict and need the difference between the dates. It would be good if we could encapsulate both the function and the data in the same object without having to create a complex class.
Well, it turns out that we can do that by subclassing Python's built-in dict, and our subclass will behave like a standard dict because it will actually be one:

Note that, unless we read the class's code, we have no clue that the keys and values are supposed to be integers and dates respectively. Not even PyCharm can help us:

We can fix that by inheriting from typing.Dict instead, which is a generic version of dict that can be annotated:

Look at the autocomplete that we have now:


Discussion (0)