DEV Community

Cover image for Python's type hints
Victor Silva
Victor Silva

Posted on • Updated on

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!

Top comments (4)

tux0r profile image

And this is only one of the problems solved by not using Python...

rapidnerd profile image
George • Edited

After using python for so long I can certainly agree with you, type hints are beautiful!

Great post, very well said.

nicoteiz profile image
Nico Oteiza

I'd never seen them before! And I've been using Python for a while already! Doesn't look very 'pythonic' IMHO, but it's definitely nice for everyone down the road

rpalo profile image
Ryan Palo

I feel like it’s one of those things where python ramps into the complexity you need. If your project is small or functions are simple, you can probably leave it off. But when you get to a point where you’re going “boy, something weird is going on. It would be nice to get some type hints,” it makes it relatively easy to add it in and get that extra help. 😁