In this lesson, you will learn:

  • what is mypy
  • how to install mypy
  • how to validate your type hints using mypy
  • mypy's main configuration options.
You can find the scripts and code for this course within the Automating Python Code Quality repo.

What is mypy?

Mypy is a static type checker for Python. It parses your type hints/annotations to find any potential issues and errors within your code. Mypy can be thought of as more of a linter, as it only reports the issues and no changes are made to your codebase.

Installing mypy

To install mypy we simply perform a poetry add -D like so:

$ poetry add -D mypy

Usage

Mypy can be run against a file or directory. For example:

$ mypy .
$ mypy dir
$ mypy myfile.py

Therefore, following on from the example in the previous lesson, let’s say we have the following file:

$ cat 003_type_checking/001_mypy_issues.py
vlan_id: int = "100"

def add_vlan(vlan_id: int):
    return vlan_id + 1

add_vlan(vlan_id)

We can now run mypy on our file (shown below). As a result, we will get the expected issue that the variable we have assigned to vlan_id is of the wrong type.

❯ mypy 003_type_checking/001_mypy_issues.py
003_type_checking/001_mypy_issues.py:1: error: Incompatible types in assignment (expression has type "str", variable has type "int")
Found 1 error in 1 file (checked 1 source file)

Configuration Options

2 main options that can be used within mypy are:

Ready to Master Network Automation? Start Your Journey Today!
Our membership provides:
  • Full deep-dive course library (inc. Batfish, pyATS, Netmiko)
  • Code repositories inc. full course code, scripts and examples
  • 24x7 multi-vendor labs (Arista, Cisco, Juniper)
  • Private online community
  • Live monthly tech sessions
  • Access to tech session library

Join Now ➜
Close You've successfully subscribed to Packet Coders.
Close Success! Your account is fully activated, you now have access to all content.
Close Welcome back! You've successfully signed in.
Close Nearly there! To activate your account, please click the link in the email we just sent you.