Python's type hints

victorosilva

Victor Silva

Posted on August 12, 2018

Python's type hints

If you've been working with Python for a little time, chances are that you've heard that explicit is better than implicit. If you've been working with Python for a long time, chances are that you strongly agree with that statement.

Today, I wanna share with you one of my favorite ways to make my Python code more explicit:

Use type hints

Let's consider the following function:

Before reading its body (which could be extremely complex), one knows neither the expected parameter type nor the return type.

Of course, we could name the function get_due_dates_dict and the parameter start_date, but that would be extremely anti-pythonic, specially when we have a much better option: type hinting via function annotations. Check it out:

Ok, now by just looking at the function's heading, we know that it expects a date and returns a dict. And just as important, any Python-aware IDE will know this as well, and will give us some nice autocompletion features.

But we can do better. We can annotate our function is such a way that we (and our IDEs) know even the structure of its return without having to read its body:

Now, it's explicit that our function returns a dict in which the keys are integers and the values are dates. In the screenshots below, we can see that PyCharm understands this perfectly, and gives us precise tips and autocompletions:

PyCharm - parameter

PyCharm - return

Type hints make everyone's life easier down the road.

That's it for today, happy coding!

💖 💪 🙅 🚩
victorosilva
Victor Silva

Posted on August 12, 2018

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Python's type hints
python Python's type hints

August 12, 2018