How do I format and lint Python code with black, flake8, and ruff?

· Category: Python Programming

Short answer

Linters and formatters enforce code quality and style automatically. black reformats code consistently, flake8 checks for style violations and errors, and ruff is an extremely fast Rust-based alternative that combines both.

Steps

  1. Install your chosen tools: pip install black flake8 ruff.
  2. Run black . to format code.
  3. Run flake8 . or ruff check . to find issues.
  4. Integrate into CI and pre-commit hooks.
black src/
flake8 src/
ruff check src/
ruff format src/

Tips

  • black is intentionally opinionated to minimize style debates.
  • isort (or ruff's built-in import sorting) keeps imports organized.
  • mypy complements linters by adding static type checking.
  • Configure tools in pyproject.toml for a single source of truth.

Common issues

  • Conflicting rules between tools can be resolved by disabling specific error codes.
  • Formatting large legacy codebases for the first time creates noisy diffs; do it in a dedicated commit.
  • Linters only catch certain classes of errors; they do not replace tests or code review.