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
- Install your chosen tools:
pip install black flake8 ruff. - Run
black .to format code. - Run
flake8 .orruff check .to find issues. - Integrate into CI and pre-commit hooks.
black src/
flake8 src/
ruff check src/
ruff format src/
Tips
blackis intentionally opinionated to minimize style debates.isort(orruff's built-in import sorting) keeps imports organized.mypycomplements linters by adding static type checking.- Configure tools in
pyproject.tomlfor 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.