MyPy IPython Demo

This shows how to use mypy to fix type errors in code.

First, load the extension.

[1]:
%load_ext mypy_ipython

Now, we need some code. Ideally code that makes a lot of type errors. Here is a function that packs a lot of errors into little code.

[8]:
def foo(s: int) -> str:
    f = s + "1"
    return 2

The next step is to run the type checker.

[9]:
%mypy
note: In function "foo":
        f = s + "1"
error: Unsupported operand types for + ("int" and "str")
        return 2
error: Incompatible return value type (got "int", expected "str")
Found 2 errors in 1 file (checked 1 source file)
Type checking failed

Oh no! Two errors in three lines. We should fix that. We should not be adding strings to integers. Let’s fix the first line in foo:

[10]:
def foo(s: int) -> str:
    f = s + 1
    return 2
[12]:
%mypy
note: In function "foo":
        return 2
error: Incompatible return value type (got "int", expected "str")
Found 1 error in 1 file (checked 1 source file)
Type checking failed

One down, one to go. We really should return a string.

[15]:
def foo(s: int) -> str:
    f = s + 1
    return "2"
[16]:
%mypy
Success: no issues found in 1 source file
Type checking successful