Make simple Python types rich

Python tips (5 Part Series)

1 Python’s type hints
2 Avoid dict overuse in Python
3 Make simple Python types rich
4 My case against the “ternary operator” in Python
5 Setup Ubuntu for Python development

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:

Sweet!

Python tips (5 Part Series)

1 Python’s type hints
2 Avoid dict overuse in Python
3 Make simple Python types rich
4 My case against the “ternary operator” in Python
5 Setup Ubuntu for Python development

原文链接:Make simple Python types rich

© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容