Check Type Hints Locally
Run mypy on a local Python file and keep static type evidence separate from runtime validation and tests.
Python does not enforce type hints when a program runs. A static type checker can read those hints before execution and point out values that do not match the declared boundaries.
This page is optional. You do not need a type checker to finish the chapter. Use one when a local program has enough functions and records that following their value flow by inspection becomes difficult.
Install Mypy in the Project Environment
From the local project environment you intend to use, install mypy through that environment's Python interpreter:
python -m pip install mypy
Then run it on a Python file:
python -m mypy report.py
Using python -m keeps the checker tied to the selected interpreter. If your
project uses a virtual environment, select that interpreter first.
Read One Mismatch
Suppose report.py contains this code:
The function says that value should be a float, but the call supplies a
str. Mypy can report that mismatch without running the program. Repair the
boundary by converting the text where it enters the computation:
The checker follows the declared types. It does not prove that every input can be converted, that a threshold is sensible, or that the result is correct. Runtime validation and tests still answer those questions.
Keep Static and Runtime Evidence Separate
| Question | Useful evidence |
|---|---|
| Does this value match the declared type? | a static type checker |
| Can this particular input be converted safely? | runtime validation |
| Does the computation produce the intended answer? | examples and tests |
A checker is most useful when its messages lead you back to a clear program boundary. Do not add hints only to silence a message; make the declared value flow match the program you intend to run.
References
Static checking inspects declared value flow before a program runs. It supports runtime validation and tests; it does not replace them.