Course contentsShow
← Python
Lesson 581 of 1,0609. Type Safety and Code QualityFree lesson

Configuring Mypy with pyproject.toml

Master the creation of project-wide configuration files to enforce consistent strictness levels and ignore specific modules or directories.

In this lesson, you will learn how to standardize your project's type-checking rules by centralizing Mypy’s configuration inside the pyproject.toml file.

Why use a configuration file?

As your project grows, running mypy manually with long lists of command-line flags becomes error-prone. By using pyproject.toml, you define your project's "strictness budget" once. This ensures that every developer on your team—and your CI/CD pipeline—evaluates your code using the exact same rules.

Structuring your pyproject.toml

Mypy looks for a [tool.mypy] section. You can define global settings here, or override them for specific modules. Here is a common setup:

[tool.mypy]
# Enable strict mode for better code quality
strict = true
python_version = "3.10"

# Ignore missing imports for third-party libraries that lack type hints
[[tool.mypy.overrides]]
module = "legacy_library.*"
ignore_missing_imports = true

# Exclude specific directories like virtual environments or temporary build files
exclude = ["venv/", "tests/legacy/"]

Key Configuration Concepts

  1. strict = true: This is the gold standard for mature projects. It enforces checking for untyped definitions, optional types, and return values, effectively preventing "type blindness."
  2. [[tool.mypy.overrides]]: Sometimes you must integrate with older code or external libraries that don't provide type information. Instead of disabling checks for the whole project, use an override to "silence" errors for that specific module while keeping the rest of your codebase strict.
  3. exclude: This prevents Mypy from wasting resources on directories that shouldn't be checked, such as auto-generated code, virtual environments, or test fixtures that aren't part of your core application logic.

By moving these settings into pyproject.toml, you transform type checking from a manual task into a project-wide policy. You no longer need to remember flags; just run mypy . from your terminal, and the tool will automatically apply your defined standards.

Key Takeaway: Centralizing Mypy configuration in pyproject.toml ensures consistent, reproducible type enforcement across your entire project while allowing granular control over specific modules and directories.