DEV Community

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

Posted on • Edited on

25 6

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:

from datetime import timedelta
def get_due_dates(start):
return {
1: start,
2: start + timedelta(days=30),
3: start + timedelta(days=60),
4: start + timedelta(days=90),
5: start + timedelta(days=120),
6: start + timedelta(days=150),
}
view raw devto0001-01.py hosted with ❤ by GitHub

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:

from datetime import date, timedelta
def get_due_dates(start: date) -> dict:
return {
1: start,
2: start + timedelta(days=30),
3: start + timedelta(days=60),
4: start + timedelta(days=90),
5: start + timedelta(days=120),
6: start + timedelta(days=150),
}
view raw devto0001-02.py hosted with ❤ by GitHub

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:

from datetime import date, timedelta
from typing import Dict
def get_due_dates(start: date) -> Dict[int, date]:
return {
1: start,
2: start + timedelta(days=30),
3: start + timedelta(days=60),
4: start + timedelta(days=90),
5: start + timedelta(days=120),
6: start + timedelta(days=150),
}
view raw devto0001-03.py hosted with ❤ by GitHub

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!

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (4)

Collapse
 
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.

Collapse
 
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

Collapse
 
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. 😁

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay