Static Type Checking with mypy

mypy reads your type hints and checks your code without running it, catching whole classes of bugs before they reach production. Python stays dynamic at runtime, but mypy gives you the safety net of a typed language during development.

Learn Static Type Checking with mypy in our free Python course — an interactive lesson with runnable examples, a practice exercise and a quick reference.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

What You'll Learn in This Lesson

Run it from the command line on a file or whole project:

With annotations, mypy spots a mismatch your program would otherwise crash on:

Plain Python would only fail when this line executes; mypy flags it immediately.

Ask mypy what type it inferred for an expression:

Use TypeVar for generic functions that preserve types:

Use Protocol for structural typing — "if it has these methods, it fits":

✔ Express intent with Optional, Union, and generics

Type hints turn Python into a safer language without giving up its flexibility.

📋 Quick Reference — mypy

You can now use mypy to catch type bugs early and keep large Python codebases reliable.

Congratulations! You've reached the end of the advanced Python track.

Practice quiz

What kind of tool is mypy?

  • A static type checker
  • A code formatter
  • A test runner
  • A runtime debugger

Answer: A static type checker. mypy analyzes your annotated code without running it, reporting type errors statically before runtime.

How do you run mypy on a file called app.py?

  • pip check app.py
  • mypy --run app.py
  • mypy app.py
  • python app.py --types

Answer: mypy app.py. You invoke the checker directly: 'mypy app.py' (or 'mypy .' for a whole project).

What does 'gradual typing' mean?

  • You must type everything at once
  • You can add type hints incrementally, mixing typed and untyped code
  • Types are inferred at runtime
  • Types are checked slowly

Answer: You can add type hints incrementally, mixing typed and untyped code. Gradual typing lets you annotate code piece by piece; unannotated parts are treated as dynamic.

Which annotation means 'an int or None'?

  • int & None