Ruff: One Fast Tool for Linting and Formatting Python
Ruff is a Python linter and formatter written in Rust. It implements rules from Flake8 and many of its plugins, sorts imports like isort, and formats code in a Black-compatible style, typically in a fraction of a second.
Install and run
uv add --dev ruff
uv run ruff check . # lint
uv run ruff check . --fix # lint and auto-fix what's safe
uv run ruff format . # format
Configure in pyproject.toml
[tool.ruff]
line-length = 100
target-version = "py313"
[tool.ruff.lint]
select = [
"E", "F", # pycodestyle errors, Pyflakes
"I", # import sorting
"B", # bugbear: likely bugs
"UP", # pyupgrade: modern syntax
"SIM", # simplifications
"S", # bandit security checks
]
ignore = ["E501"] # line length is handled by the formatter
[tool.ruff.lint.per-file-ignores]
"tests/**" = ["S101"] # assert is fine in tests
Examples of what it catches
import os, sys # F401: 'sys' imported but unused; I001: unsorted imports
def add_item(item, items=[]): # B006: mutable default argument
items.append(item)
return items
if x == None: # E711: comparison to None should be 'is None'
pass
Run it automatically
# .pre-commit-config.yaml
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: vX.Y.Z # the Ruff version your project uses
hooks:
- id: ruff
args: [--fix]
- id: ruff-format
# CI: fail if anything needs fixing
ruff check . && ruff format --check .
Install the Ruff editor extension too, so issues show up while you type.
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.