In this lesson, you will learn how to transition from using static type hints as documentation to enforcing them automatically by installing and running mypy locally.
Installing Mypy
Mypy is a command-line tool that acts as a static analysis engine for your Python code. To get started, you can install it into your local environment using pip:
pip install mypy
Once installed, it becomes a part of your development toolkit, allowing you to catch type-mismatch bugs before you even run your program.
Running Type Checks
The simplest way to use mypy is to run it against a specific file from your terminal. Suppose you have a file named app.py containing a function annotated to take an int, but you accidentally pass it a str:
def greet(age: int) -> None:
print(f"You are {age} years old.")
greet("twenty")
When you run the following command in your terminal:
mypy app.py
mypy will analyze the syntax tree and return an error message: Argument 1 to "greet" has incompatible type "str"; expected "int". This immediate feedback is invaluable for preventing runtime TypeError exceptions.
Streamlining Development
For larger projects, you can run mypy on an entire directory or configure it to check your codebase whenever you save a file. If you want to enforce strictness, you can use the --strict flag:
mypy --strict .
This flag forces mypy to complain about missing type annotations, untyped function definitions, and other loose coding practices. By integrating this into your workflow, you create a "type-safety net" that continuously validates your architecture against the constraints you defined earlier in this course. It ensures that as your project scales, your type definitions remain a source of truth rather than just suggestions.
Key Takeaway: Installing Mypy locally allows you to catch type errors during development, providing a robust, automated layer of verification that ensures your code adheres to the signatures you have defined.