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:
Type hints make everyone's life easier down the road.
That's it for today, happy coding!
Top comments (4)
After using python for so long I can certainly agree with you, type hints are beautiful!
Great post, very well said.
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
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. 😁