Code Quality: Ruff, Mypy, Formatting & pre-commit
Maintaining enterprise code quality in Python requires automating linting, code formatting, static type checking, and Git commit validation. Modern Python engineering relies on Ruff (an ultra-fast Rust-based linter and code formatter replacing Black, Flake8, and Isort), Mypy for static type checking, and pre-commit for automated git hook enforcement.
This chapter details the unified Ruff tooling engine, Mypy static analysis configuration, pyproject.toml quality settings, and pre-commit Git hook integration.
1. The Modern Tooling Paradigm: Ruff
Historically, Python code quality required chaining 5 separate tools (black for formatting, flake8 for linting, isort for import sorting, pyupgrade for modern syntax, and autoflake).
Ruff consolidates all these tools into a single Rust binary operating 10-100x faster than Python-based linters:
Tooling Evolution:
Legacy Pipeline: [ Black ] ββ> [ Flake8 ] ββ> [ isort ] ββ> [ pyupgrade ] (~5-15 Seconds)
Modern Pipeline: [ Ruff (Rust Single Binary: Linting + Formatting + Sorting) ] (~0.05 Seconds!)Key Ruff Advantages:
- Zero Configuration Boilerplate: Single
pyproject.tomlconfiguration section ([tool.ruff]). - Auto-Fixing (
ruff check --fix): Automatically fixes hundreds of lint errors (unused imports, legacy syntax, formatting). - Format Parity: Implements Black-compatible code formatting (
ruff format).
2. Declarative Tooling Configuration (pyproject.toml)
Centralize all code quality tool settings inside pyproject.toml:
[tool.ruff]
line-length = 88
target-version = "py311"
[tool.ruff.lint]
select = [
"E", # pycodestyle errors
"F", # Pyflakes bugs
"I", # isort import sorting
"B", # flake8-bugbear logic flaws
"UP", # pyupgrade modern syntax recommendations
]
ignore = ["E501"] # Line length managed by ruff format
[tool.mypy]
python_version = "3.11"
strict = true
warn_return_any = true
warn_unused_configs = true
disallow_untyped_defs = true3. Automated Git Validation with pre-commit
Relying on developers to run linters manually leads to dirty commits. pre-commit runs quality checks automatically on git commit:
# .pre-commit-config.yaml
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.3.0
hooks:
- id: ruff
args: [--fix]
- id: ruff-format
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.8.0
hooks:
- id: mypy
additional_dependencies: [types-requests]Installation:
pre-commit install # Installs git hook inside .git/hooks/pre-commit4. Production CI/CD Gate Enforcement
Always enforce quality gates in your GitHub Actions or GitLab CI/CD pipelines:
# .github/workflows/ci.yml
jobs:
quality:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: astral-sh/setup-uv@v1
- run: uv run ruff check .
- run: uv run ruff format --check .
- run: uv run mypy src/