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.
pip install mypy
Python code
21 linesfrom 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
{'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
- Set `strict = true` in a `mypy.ini` file instead of using the CLI flag.
- 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
More from Modern tooling
- Build a Recipe Runner Mock in Python easy
- Build a Textual TUI App Skeleton in Python easy
- Configure ruff linter rules in pyproject.toml with Python easy
- Data Conversion Helper Functions in Python easy
- How to Bind and Mock structlog Context in Python medium
- How to Build a Chainable Filter Helper in Python easy
Keep learning
Related tutorials and quizzes for this topic.