Aller au contenu

Mypy

Mypy is a static type checker for Python.

Configuration dans un projet

pyproject.toml
[tool.mypy]
packages = ["src", "tests"]
cache_dir = "/dev/null"     # Linux
# cache_dir = "nul"         # Windows
mypy_path = "stubs"
ignore_missing_imports = true

Configuration globale

~/.mypy.ini
[mypy]
ignore_missing_imports = true

Utilisation

Générer les stubs du projet

stubgen src --output stubs

Lancer le linter

mypy

Utilisation avec pre-commit

Configuration

.pre-commit-config.yaml
repos:
  - repo: https://github.com/pre-commit/mirrors-mypy
    rev: v1.13.0
    hooks:
      - id: mypy
        args: ["--config-file", "pyproject.toml"]
        additional_dependencies:
          [
            # Same dependencies as in 'pyproject.toml'.
          ]

Utilisation

pre-commit run --all-files mypy

Intégration à Visual Studio Code

.vscode/extensions.json
{
    "recommendations": [
        "ms-python.mypy-type-checker",
    ],
}
.vscode/settings.json
{
    "mypy-type-checker.path": [
        "${workspaceFolder}/venv/bin/mypy"                 // Linux
        // "${workspaceFolder}\\venv\\Scripts\\mypy.exe"   // Windows
    ],
    "mypy-type-checker.interpreter": [
        "${workspaceFolder}/venv/bin/python"               // Linux
        // "${workspaceFolder}\\venv\\Scripts\\python.exe" // Windows
    ],
}

Ressources