Meet Type Hints and mypy

15 Sep 2018

It has really been a while since last time I posted something on the blog. Let’s get the rhythm back again with this post.

Recently I started using Type Hints in Python 3. And I also started to use mypy to do static type checking based on type hints.

I can understand the purpose of introducing Type Hints and mypy: a static typing system to help the machine (in this case mypy , other static checkers and whatever tools, like IDE) to check the types of your code at compile time. This can help you spot certain bugs earlier while building larger software system with Python. And in some ways, the type annotations might make your code easier to understand. For example, see the following code:

#!/usr/bin/env python

def f(n: int) -> str:
    return str(n)

f('OMG')

And save it as mypy-example.py, then if you run mypy against this file:

$ mypy mypy-example.py
mypy-example.py:6: error: Argument 1 to "f" has incompatible type "str"; expected "int"

Mypy actually helped you catch a bug here! However, I do have to say, since you need to add type hints in your code to make this work, it does add some overhead to development compared to traditional python programs.

Now, here are some of the tips I collected over using Type Hints and mypy:

Side Note on Ellipsis

Ellipsis ... is actually a valid Python expression which represents the singleton Ellipsis object.

It is originally from numpy package for advanced slicing notation. But it is now also used as:

  1. A place holder for not-yet-written code.
  2. Specify type hints using typing module (like what we saw above).
  3. As a default argument value, especially when you want to distinguish between not passing a value and passing in None.

Useful Reference Regarding Mypy and Type Hints