Not everyone likes Black formatting, but what I like less is arguing about formatting. Use Black and be done with it. Or use Ruff and be done with it faster. Ruff is a linter and formatter implemented in Rust so it’s fast, very fast.
Here’s a recipe to implement autoformatting with Ruff for a Github repo and VSCode IDE.
Configure Ruff
Configure how ruff runs by adding the following to the pyproject.toml
file
[tool.ruff]
cache-dir = ".ruff-cache"
src = ["src", "tests"]
[tool.ruff.format]
docstring-code-format = true
docstring-code-line-length = 80
line-ending = "lf" # Use `\n` line endings always
[tool.ruff.lint]
# Sort imports
extend-safe-fixes = ["I001"]
# Lint isort codes
extend-select = ["I"]
[tool.ruff.lint.per-file-ignores]
# Ignore unused imports for convenience imports
"__init__.py" = ["F401"]
[tool.ruff.lint.isort]
known-local-folder = ["package-name", "tests"]
known-first-party = [
... add any first party packages here ...
]
and add .ruff_cache
to .gitignore
.
Setup IDE formatting
We want to configure VSCode to use Ruff as the default formatter and format
on save.
To achieve this, add the following to the VSCode config or to devcontainer.json
file
{
"extensions": [
"charliermarsh.ruff",
],
"settings": {
"[python]": {
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll": "explicit",
"source.organizeImports": "explicit"
},
"editor.defaultFormatter": "charliermarsh.ruff"
}
}
}
Configure pre-commit hooks
Pre-commit git hooks will ensure all committed changes conform to the newly
configured formatter.
This is most easily achieved with the pre-commit
library.
Install pre-commit>=3.6.2
and add it to the requirements;
create .pre-commit-config.yaml
and add
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: v0.4.5
hooks:
# Run the linter.
- id: ruff
args: [ --fix ]
# Run the formatter.
- id: ruff-format
then install with pre-commit install
.
Configure PR hooks
Finally, configure server-side git hooks for safety - in case colleagues haven’t
configured their local setups correctly and try to commit unformatted code.
This uses github actions, so create .github/workflows/ruff.yaml
and add
name: Ruff
on: [push, pull_request]
jobs:
ruff:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: chartboost/ruff-action@v1
- uses: chartboost/ruff-action@v1
with:
args: 'format --check'
Note, this action is currently untested.
Posted Friday 24 May 2024 Share
- You might also like: