Python MyPy – Static Type Checking Tutorial

In this Python Tutorial we will talk the MyPy library. The MyPy library is a static type checker in Python, whose purpose is to enable the writing and checking of statically typed code. It verifies the types that you’ve used in the code, and raises an error if any contradiction is found.


Installing MyPy

As MyPy is a library not included in the Python Standard Library, it needs to be downloaded separately. You can easily do so using the following command, or any equivalent to it.

pip install mypy

You aren’t meant to actually import the mypy library into your code. Rather you need to use it to execute your Python code, instead of using the default Python interpreter.

You need to make use of a terminal, which can either be the command prompt or a built-in-terminal in an IDE like Visual Studio Code. The following command needs to be executed.

mypy filename.py

In case the above command does not work, try following one.

python -m mypy filename.py

Also remember that if you are executing this command from a different directory, then you will need to include the full path of the file. So it might end up something like this.

mypy "C:/Users/Coder/Desktop/filename.py"

For a few additional options that we can use with the mypy static type checker, refer to the end of the tutorial.


Static Type Checking with MyPy

Let’s discuss with examples, several code snippets where we use MyPy to perform static type checking on some Python code.

Using MyPy with Primitive Types

Now let’s try using MyPy with some of the basic types in Python, such as int, str, bool and float. The format is simple. We write the variable name as usual, then the type we want it to be, separated by a colon. We can also optionally assign it an initial value.

Here is us declaring a variable of a type int.

myint: int = 5
myint = "Hello"    # Throws error
typehinting.py:5: error: Incompatible types in assignment (expression has type "str", variable has type "int")
Found 1 error in 1 file (checked 1 source file)

A variable of type float.

myfloat: float 
myfloat = 1.23   
Success: no issues found in 1 source file

A variable of type string.

mystring: str = "Hello"
mystring = 5         # Throws error  
typehinting.py:4: error: Incompatible types in assignment (expression has type "int", variable has type "str")
Found 1 error in 1 file (checked 1 source file)

As you can see, wherever we assign the incorrect type to a variable, it throws an error.

Here we have a function that prints out a string “n” number of times. The first parameter must be a string, whereas the second must be an integer. Enforcing this with type hinting helps ensure we don’t run into a logic error.. For example, where our code prints out something other than a string.

def printString(string: str, count: int):
    for i in range(count):
        print(string)

printString("Hello World", 5)
Hello World
Hello World
Hello World
Hello World
Hello World

Using MyPy with Python Typing Library

To enhance our type hinting experience in Python we have the Python Typing Library. Normally we can only hint the types for variables and function return types, but with the Typing library we can hint for containers like Lists and Dictionaries as well.

Here we have both a list of floats, and a dictionary with strings as keys and integers as values.

from typing import List, Dict

mylist: List[float] = [ 1.23, 4.56, 7.89 ]

mydict: Dict[str, int] 
mydict["1"] = 5

There are other cool things we can do too, like Union of types, which allows us to specify more than just one type. The variable in the example below accepts both strings and integers, hence no error is raised when using multiple types.

from typing import Union

myVar: Union[int, str]

myVar = 1
myVar = "Hello"
Success: no issues found in 1 source file

For a complete tutorial on the Typing Library, check out our dedicated tutorial for implementing type hinting in Python.


MyPy Commands

Normally, when MyPy runs, any variables and function parameters that haven’t been type hinting will be ignored. MyPy will only verify those which have type annotations on them. But if we enable a special option, when running mypy in the terminal, it will raise an error on missing types.

$ mypy --disallow-untyped-defs test.py

Thus, this ensures that every variable and parameter has been type hinted.

There are a bunch of other similar commands like this, but if you want an All-in-One solution, you can use the –strict option.

$ mypy --strict test.py 

This marks the end of the Python MyPy Static Type Checking Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments