How to set up mypy strict mode in Python

Demonstrates how to configure and run mypy in strict mode to enforce full type annotation coverage across a Python project.

Medium Python 3.9+ Aug 9, 2026 Modern tooling 14 views 0 copies

Requires third-party packages — install first
pip install mypy

Python code

21 lines
Python 3.9+
from typing import Dict, Optional


def describe_user(name: str, age: int, email: Optional[str] = None) -> Dict[str, object]:
    """Build a user description dictionary with strict type annotations."""
    user: Dict[str, object] = {"name": name, "age": age}
    if email is not None:
        user["email"] = email
    return user


def main() -> None:
    user_a: Dict[str, object] = describe_user("Alice", 30, "alice@example.com")
    user_b: Dict[str, object] = describe_user("Bob", 25)

    for user in (user_a, user_b):
        print(user)


if __name__ == "__main__":
    main()

Output

stdout
{'name': 'Alice', 'age': 30, 'email': 'alice@example.com'}
{'name': 'Bob', 'age': 25}

How it works

mypy strict mode enables a set of flags that enforce complete type annotation coverage, including requiring annotations on function definitions and variables. It also disables implicit Optional and requires explicit handling of None and Any types. This code uses Optional[str] for the email parameter and Dict[str, object] for return types to satisfy those checks. Running mypy --strict on this file passes cleanly, validating that all types are correctly annotated.

Common mistakes

  • Forgetting to annotate module-level variables or function parameters, which strict mode requires.
  • Using `Dict` without specifying both key and value types, or using `Any` implicitly via untyped values.
  • Running mypy without the `--strict` flag and assuming the config is applied.
  • Not handling `None` explicitly with `Optional` when a parameter can be `None`.

Variations

  1. Set `strict = true` in a `mypy.ini` file instead of using the CLI flag.
  2. Use `TypedDict` for the user description to get more precise types than `Dict[str, object]`.

Real-world use cases

  • Enforcing complete type annotations in a shared library's public API to prevent misuse by consumers.
  • Catching potential `None` handling bugs in a data processing pipeline before code reaches production.
  • Adding a `mypy --strict` check to CI to block merges of untyped or loosely typed Python code.

Sponsored

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Modern tooling

Related tutorials and quizzes for this topic.