Static type checking with mypy

Documentation

  1. mypy
  2. Getting started

Install the mypy program

pip3 search mypy
mypy (0.761)                                 - Optional static typing for Python

pip3 install mypy

pip3 list
Package           Version
----------------- ---------
mypy              0.761
mypy-extensions   0.4.3

pip3 show mypy
Name: mypy
Version: 0.761
Summary: Optional static typing for Python
Home-page: http://www.mypy-lang.org/
Author: Jukka Lehtosalo
Author-email: jukka.lehtosalo@iki.fi
License: MIT License
Location: /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-package
Requires: mypy-extensions, typed-ast, typing-extensions
Required-by:

pip3 show --files mypy | cat -n

which mypy
/Library/Frameworks/Python.framework/Versions/3.8/bin/mypy

mypy --version
mypy 0.761

mypy --help

Dynamic checking

The expression 10 + "A" is erroneous. Normally, Python checks for this error only in statements that are executed as the program runs. This is called dynamic checking.

"This program is prog.py."
import sys
import random

if random.randrange(2) == 0:   #fifty-fifty chance
    print(10 + "A")

print("Everything is okay.")
sys.exit(0)

There is only a fifty-fifty chance that the error will be detected:

Everything is okay.
Traceback (most recent call last):
  File "/Users/myname/python/prog.py", line 6, in <module>
    print(10 + "A")
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Static checking

mypy will check every statement of your Python program, but without executing these statements. This is called static checking.

mypy prog.py
prog.py:6: error: Unsupported operand types for + ("int" and "str")
Found 1 error in 1 file (checked 1 source file)