How do I use `mypy` for type checking

Mypy is a powerful static type checker for Python that allows you to check the type correctness of your Python code. It is particularly useful for larger codebases and helps catch bugs before runtime. To use mypy for type checking, follow these simple steps:

Installation

First, you need to install mypy. You can do this using pip:

pip install mypy

Basic Usage

Once installed, you can run mypy on your Python files. For example:

mypy your_script.py

Adding Type Annotations

To take full advantage of mypy, add type annotations to your functions and variables. For instance:

def greet(name: str) -> str: return 'Hello, ' + name

Running Mypy

After adding type annotations, run mypy again to check for any type errors:

mypy your_script.py

Make sure that your code is type-safe by addressing any issues reported by mypy.


mypy type checking Python static type checker bug detection