Mypy

Page content

mypy

Know what you are getting and ideally what you are giving.

mypy has the lofty goal to add typing to Python. It’s available as usual from pypi. The package actually contains a checker that will walk through your code and test all the types are pbeing passed correctly.

The first question is usually “Why?”. From the mypy site: “Mypy combines the expressive power and convenience of Python with a powerful type system and compile-time type checking.”. It works by adding a flexible level of checking if the type you are passing is correct. Like most checkers it works best when the whole code base is covered by types. Complete coverage isn’t essentially and even just a few methods with types could be enough to save from you from a production exception when your assumption about a parameter doesn’t pay off.

More information can be found in the Python docs here.

Testing

Once you have all your code typed you can run mypy over all the source files to ensure all is well and everything is as expected.

mypy src/*

Examples

Constructers

As usual constructers are little bit specical. __init__ always returns a None. In the case beloew __init__ is expecting a List.

A nice shortcut is to import typing as t this will make save typing when you need a type. As a rule it’s best to use the typing to maintain a constant definition of a type.

import typing as t

class ResultSet:

    def __init__(self, results: t.List[str]) -> None:
        self.results = results

Mixing Types

One area of concern is handling multiple types of parameters. This is done by using the Union type, this takes a list of valid types.

from typing import Union 
def caribbean_chilli(self, results: Union[str, int]) -> None:
        return "hot!"