Ruff is a high performance Python linter and formatter.
Ruff is both a Python tool and Python package. Think of it this way:
$ pip install ruffWhen you install it, you get the ruff command-line tool:
# To link a directory
$ ruff check .
# To format code
$ ruff formatSo technically
ruff (python package)
| Installs
ruff (CLI tool)| Purpose | Traditional Tool | Ruff |
|---|---|---|
| Formatting | Black | YES |
| Linting | Flake8 | YES |
| Import Sorting | isort | YES |
| Unused Imports | Pyflakes | YES |
| Code Style Checks | pylint plugins | YES |
| Auto-fixing Issues | Autoflake | YES |
- pyproject.toml
or
- ruff.toml
or
- .ruff.tomlConsider this code:
# Filename: app.py
import os
import json
def hello():
print("hello")
here json is unused.
Now, Run:
$ ruff check app.pyOutput:
F401 `json` imported but unusedLets auto fix it now. Run this code,
$ ruff check --fix app.pyRuff automatically removes import json so now code will look like
# Filename: app.py
import os
def hello():
print("hello")
Ruff can also format code.
Before:
def add(a,b): return a+bRun:
$ ruff format .After:
def add(a,b):
return a+bUsing pyproject.toml :
[tool.ruff]
line-length = 88
target-version = "py3111"
[tool.ruff.format]
quote-style = "single"
[tool.ruff.lint]
select = [
"E", # pycodestyle errots
"F", # Pyflakes
"I", # Import sorting
"B" # Bugbear checks
]
ignore = ["E501"] # ignore line-length errors
Ruff is commonly run as a quality gate in Github Actions or in any CI pipelines. The idea is simple:
Create:
<your-python-repo>
.github/
|___workflows/
|___ci.yml
src/
|____pyproject.tomlname: Python CI
on:
pull_request:
push:
branches:
- main
jobs:
quality_gate:
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v4
- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Install Dependencies
run: pip install -r requirements.txt
- name: Ruff Check
run: ruff check .
- name: Format Check
run: ruff format --check .
The Ruff VS Code Extension is an official extension developed by Astral that integrates the blazing-fast Rust-based Python linter and formatter directly into your editor.
To get the most out of the extension, you should configure it to automatically organize imports and format your Python files every time you save. Open your user settings.json file in VS Code and append the following configuration:
{
"[python]": {
"editor.defaultFormatter": "charliermarsh.ruff",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports.ruff": "explicit",
"source.fixAll.ruff": "explicit"
}
}
}For more details check this link.