Sub topic 3
Suppressing Ruff Violations in a Python Project
Assume you know basic Python, can use a terminal and virtual environment, and can read pyproject.toml. Ruff reports problems, but some lines are intentional. Suppress those cases narrowly and document why.
Use `noqa` Comments
Add # noqa: CODE to suppress one rule on one line. For example, F401 means an imported name is unused.
import os # noqa: F401
def compute():
return 42
value = compute() # noqa: F841
print(value)A bare # noqa suppresses every rule on that line. Prefer a named code because it keeps future violations visible.
from package import public_api # noqa: F401Ignore Rules for Specific Files
Use per-file ignores when a whole file has a deliberate convention. This example permits unused imports in package initializer files:
[tool.ruff.lint.per-file-ignores]
"__init__.py" = ["F401"]Do not use a broad ignore to hide unrelated defects. A targeted file pattern and rule list are easier to review.
Sort Imports with Ruff
Ruff's I rules provide isort-compatible import sorting. Enable them with a rule prefix:
[tool.ruff.lint]
select = ["E4", "E7", "E9", "F", "I"]Run ruff check --fix . to apply safe import changes. Review the result when local modules, optional dependencies, or unusual package layouts affect import grouping.
Avoid Linter and Formatter Conflicts
ruff check finds lint violations. ruff format changes layout, spacing, and quotes. Run the formatter before lint autofixes, then run both checks again.
ruff format .
ruff check --fix .
ruff format --check .
ruff check .Keep formatting choices in one configuration. Avoid enabling another formatter that rewrites the same lines.
Automate Ruff
A pre-commit hook catches issues before commits. CI should verify rather than silently change files:
- id: ruff-check
args: [--output-format, concise]
- id: ruff-format
args: [--check]Pin Ruff's version so local and CI results agree.
Editor and Migration Choices
Install the Ruff extension for your editor and enable format-on-save if your team agrees. Disable competing Flake8, isort, or Black formatters for the same files.
During migration, compare Ruff with existing tools, enable equivalent rule families, format a dedicated branch, and review the diff. Ruff can replace much of Flake8, isort, and Black, but confirm plugin-specific rules before removing them.
Exercise
Which suppression is safer: # noqa or # noqa: F401, and why?
Show answer
# noqa: F401 is safer because it suppresses only the intentional unused-import warning.