Type Annotations in Python 3.8

Martin Thoma
Analytics Vidhya
Published in
6 min readJun 22, 2020

--

Image Source: Benjamin Hell

One reason why Python is so easy to get started with is that it has dynamic types. You don’t have to specify the type of a variable, you just use variables as labels for containers of data. But in bigger projects, having types is helpful. If you have an undocumented function without types and maybe crappy variable naming, new developers will have a hard time. Luckily, variable annotations were added in Python 3.6 with PEP 526 🎉

This article is written in such a way that you can easily stop after the “mypy” section and take only a look at individual sections then.

Hello, Typed Annotated World!

So you can simply use the pattern

def some_function(param_name : typename) -> return_type_name:
... # whatever the function does

Having type annotations is nice, but you need to check them! The Python runtimes do not do that, no matter if you use CPython, pypy, or something more exotic.

Type Checking with mypy

Install mypy via pip install mypy and run it:

$ mypy . --ignore-missing-imports
Success: no issues found in 1 source file

The --ignore-missing-imports flag is necessary because otherwise you will get a lot of messages like this:

--

--

Martin Thoma
Analytics Vidhya

I’m a Software Engineer with over 10 years of Python experience (Backend/ML/AI). Support me via https://martinthoma.medium.com/membership