Mypy#

Mypy is a static type checker for python. Check official documentation.

Get mypy types#

Mypy has it’s own type detection system, so sometimes it’s useful to know how to check what type it’s detecting. You can do this using the reveal_type and reveal_locals functions.

Note You don’t need to import them or something mypy will understand them by itself.


Here is an example of the reveal_type function, which allows you to understand how mypy interprets the type of a given name.

%%writefile /tmp/mypy_reveal_type.py
import numpy as np
reveal_type(np.pi)
Writing /tmp/mypy_reveal_type.py
!python3 -m mypy /tmp/mypy_reveal_type.py
/tmp/mypy_reveal_type.py:2: note: Revealed type is "builtins.float"
Success: no issues found in 1 source file

And an example of reveal_locals, which prints out information about all the variables in the namespace.

%%writefile /tmp/mypy_reveal_locals.py
my_float = 10.
my_int = 10

reveal_locals()
Overwriting /tmp/mypy_reveal_locals.py
!python3 -m mypy /tmp/mypy_reveal_locals.py
/tmp/mypy_reveal_locals.py:4: note: Revealed local types are:
/tmp/mypy_reveal_locals.py:4: note:     my_float: builtins.float
/tmp/mypy_reveal_locals.py:4: note:     my_int: builtins.int
Success: no issues found in 1 source file

Wrong syntax#

The Python interpreter doesn’t throw exceptions even if there are annotations that are defined incorrectly. But mypy will throw errors on it’s side.


Here is an example where we are trying to annotate the dictionary, but instead of annotating key and value types, we have only annotated one.

%%writefile /tmp/mypy_wrong_syntax.py
my_dict: dict[int]
Writing /tmp/mypy_wrong_syntax.py

If you try to run it just with the python interpreter, it works fine.

!python3 /tmp/mypy_wrong_syntax.py

But mypy raises corresponding error.

!python3 -m mypy /tmp/mypy_wrong_syntax.py
/tmp/mypy_wrong_syntax.py:1: error: "dict" expects 2 type arguments, but 1 given  [type-arg]
Found 1 error in 1 file (checked 1 source file)