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.
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.
To install mypy we simply perform a
poetry add -D like so:
$ poetry add -D mypy
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)
2 main options that can be used within mypy are: