Advantages of using type hints

Hey there, 👋

How is your Python going?

In this Mathspp Insider 🐍🚀 email we’ll talk about some advantages of using typing with Python.

This email at a glance

  • Typing speeds up development time, even if your codebase is only partially typed;

  • typing lets you use static type-checkers which will catch bugs before your code runs;

  • typing lets you use runtime type-checking tools that do data conversions/validation for you;

  • typing can make your code run faster; and

  • there are only 3 days left to join 65+ others for the Python Problem-Solving Bootcamp.

Problem-solving on steroids

I can give your Python 🐍 skills an unfair advantage for 2024. 🚀

In 3 days I'm running a Python problem-solving bootcamp.

It's fully asynchronous, you'll solve 42 challenges, and you'll learn things like:

  • 🧐 how to use syntactic Python elements like assignment expressions, conditional expressions, list comprehensions, and more;

  • 🛠️ how to use modules like collections, itertools, functools, and more; and

  • ✨ how to combine tools you’ve been using forever into new idioms that are expressive and powerful.

To top it all off,

  • 📚 you'll also get a bonus PDF with all the challenges and multiple solutions with a full analysis written by me.

Join the 65+ others who'll start 2024 with an unfair advantage.

Join by clicking the button below.

To type or not to type?

Python typing is a pretty polarising issue.

There’s people who never heard of it, which is fine.

And then there’s people who love it and people who hate it.

If you don’t know what typing/type hints are, you may want to read PEP 483.

While I do have a personal opinion about type hinting (which I’m fine sharing if you ask), in this email I’ll try to lay out a couple of objective advantages of using type hints in your code.

Autocompletions & development speed

If your code is typed, even if only partially, your development speed increases, which means you take less time to write the same code.

That’s essentially because, with type hints, your IDE will provide helpful autocompletions when you are accessing attributes and methods on your objects.

It can also serve as a memory aid!

Suppose I have a class with an attribute time_elapsed.

I’m a very forgetful person, so I’ll eventually forget whether the attribute was called time_elapsed or elapsed_time or something else.

If I type just a ti, the IDE will show the completion for time_elapsed and I’ll know it was time_elapsed!

Static type-checking

By using type-hints in your code tools like mypy can analyse your code statically (that is, without running your code) and detect some logical errors in your code.

For example, the function is_even below has an obvious bug:

def is_even(number: int) -> bool:
    if number % 2 == 0:
        return True

The bug here is that we’re not returning False when the number is odd.

If the input is an odd number, the return value is None, which is definitely not a Boolean value, right?

So, when a tool like mypy analyses the function is_even, it understands that the function has an implicit return None at the end and it understands that the None is incompatible with the Boolean (bool) that the function was supposed to return.

Thus, mypy will complain that there is an issue with is_even.

Now, this example was very small and it was very easy to spot the mistake by hand.

This isn’t always the case, though, otherwise there would be no bugs in the whole world.

Personally, one specific case where static type-checking helps me a lot is when I work with attributes from different classes.

Some attributes can be set to None to indicate that no value was set yet and sometimes I forget about that.

So, suppose that an attribute person.names is a list with the names, except that it’s set to None if the person hasn’t been initialised yet.

If I write something like person.names.append("Rodrigo") without checking if names was already initialised, mypy will let me know that names may be None!

Runtime type-checking

Type hints can also be used at runtime by tools that inspect type hints explicitly.

Tools like Typer and Pydantic use type-hints at runtime to change the way your code works.

For example, Typer is a library to write CLI programs and it uses type hints to determine how to parse the user input.

As another example, Pydantic uses type-hints to do data validation and data conversion while your program runs!

You won’t use these tools all the time, but they are very powerful and they are powered by type hints.

Performance

In some cases, having typed code can actually improve your performance.

If you use a tool like mypyc, you can compile your Python code and your code will run faster.

I don’t think this should come as a complete surprise, though, given that compiled languages are typically faster than interpreted languages.

I can’t say much about this, though, because I’ve never used mypyc before.

Conclusion

If you’re on the fence about learning type hinting, consider these advantages as points in favour of learning it.

However, don’t forget that there are no free lunches and obviously type hinting has disadvantages, too.

If you think I forgot to mention a specific advantage of type hinting or if you have any thoughts about type hinting, feel free to reply to this email!

I need your opinion

I sent an email about divmod yesterday and I sent an email today, although today is the day when I usually email you.

How do you feel about more than 1 email per week?

ICYMI

In Case You Missed It, this past week

🐍🚀 How was this email?

Login or Subscribe to participate in polls.