Sub topic 1
What Ruff Is and What It Replaces
Prerequisites
You should know basic Python syntax, how to run a script, and how to use a terminal. You should also know how to install packages with pip and read a simple pyproject.toml file. Ruff runs on Python projects but does not replace Python itself or your test runner.
Ruff as One Python Tool
Ruff is a fast command-line tool for checking and formatting Python code.
A linter examines source code and reports likely errors, bugs, and style problems. A formatter rewrites code into a consistent layout. Ruff provides both jobs:
ruff checkruns lint rules.ruff formatformats Python files.
Ruff can replace several separate tools:
| Older tool | Ruff equivalent |
|---|---|
| Flake8 and many plugins | `ruff check` |
| isort | Ruff import-sorting rules |
| Black | `ruff format` |
Ruff does not replace a type checker such as mypy or a test framework such as pytest.
Installing and Invoking Ruff
Install Ruff in the project's virtual environment:
pip install ruffRun it from the project directory:
ruff check .
ruff format .The dot means “the current directory.” You can also provide a file or directory, such as ruff check src.
Finding Problems with `ruff check`
Consider this file:
import os
import sys
def total(items):
unused = 1
result = 0
for i in items:
result += i
if result == None:
return 0
return result
print(sys.argv)Run:
ruff check example.pyRuff reports unused imports, the unused local variable, and the comparison with None. Each report includes a location, a rule code, and a message. The command exits with a nonzero status when violations remain, which makes it useful in automation.
Reading Rule Codes
Rule codes identify the rule that produced a diagnostic. F401 means an imported name is unused. F841 means a local variable is assigned but never used. E711 identifies an inappropriate comparison with None; use is None instead.
The first letter identifies a rule family. A prefix such as F can select the whole family, while F401 selects one rule. Use ruff rule F401 to read Ruff's documentation for a rule.
Exercise
Which command checks a project without formatting it, and what does F401 mean?
Show answer
ruff check . checks the project. F401 reports an imported name that is never used.