Sub topic 2
Configuring Ruff in `pyproject.toml`
Assume you know basic Python, can use a terminal, and have used a virtual environment. Ruff reads project settings from pyproject.toml, so the same rules apply locally and in CI.
Configuring Ruff
Create or update this section:
[tool.ruff]
line-length = 88
target-version = "py311"
[tool.ruff.lint]
select = ["E4", "E7", "E9", "F", "I", "B", "UP"]
ignore = []
[tool.ruff.lint.per-file-ignores]
"__init__.py" = ["F401"]
[tool.ruff.format]
quote-style = "double"
indent-style = "space"
docstring-code-format = trueline-length sets the preferred maximum line length. target-version tells Ruff which Python syntax is available. The lint section controls diagnostics, while the format section controls formatting.
Choosing Rules
A rule code identifies a kind of problem. For example, F401 means an imported name is unused. A prefix selects a family of rules:
| Setting | Meaning |
|---|---|
| `"E4"` | Select rules whose codes start with `E4` |
| `"F"` | Select all Pyflakes rules |
| `"I"` | Select import-sorting rules |
| `"B"` | Select flake8-bugbear rules |
Start with a small, understood set. Add rule families after reviewing their reports. Use ignore for project-wide exceptions and per-file-ignores when an exception belongs only to certain files.
Fixing Violations Automatically
Run the linter and formatter separately:
ruff check .
ruff check --fix .
ruff format .
ruff format --check .ruff check --fix applies safe fixes, such as removing an unused import or sorting imports. It does not apply fixes that might change behavior unless you request them with --unsafe-fixes. Review the diff after any automatic fix.
Formatting with `ruff format`
ruff format applies deterministic spacing, quotes, and blank-line rules. It is compatible with the style used by Black. Use ruff format . to change files and ruff format --check . in CI to fail when files are not formatted.
Run formatting before linting in local workflows. Then run the checks again and inspect changes that remain.
Exercise
Which command checks formatting without modifying files?
Show answer
ruff format --check .