Ruff¶
Ruff is an extremely fast Python linter and code formatter written in Rust that can enforce the rules of flake8, isort, perflint, Black, Bandit, and others. In total, Ruff can check over 800 rules.
Installation¶
$ uv add --dev ruff
Check¶
You can then check the installation with
$ uv run ruff check /PATH/TO/YOUR/SOURCE/FILE
Shell auto-completion¶
Ruff supports autocompletion for most shells. A shell-specific script can be
generated with uv run ruff generate-shell-completion SHELL, where
SHELL is either bash, elvish, fig, fish,
powershell or zsh, for example
$ ruff generate-shell-completion zsh >> ~/.bash_completion
% ruff generate-shell-completion zsh > ~/.zfunc/_ruff
Then, the following lines must be added to your ~/.zshrc file, if
they are not already there:
fpath+=~/.zfunc
autoload -Uz compinit && compinit
% mkdir $ZSH_CUSTOM/plugins/ruff
% ruff generate-shell-completion zsh > $ZSH_CUSTOM/plugins/ruff/_ruff
See also
Configuration¶
Unlike Black’s default formatting of 88 characters, I prefer a line
length of 79 characters. To do this, you can enter the following in the
pyproject.toml file:
[tool.ruff]
line-length = 79
Tip
Usually, we first add all rules to ruff lint before excluding individual
ones, for example:
[tool.ruff.lint]
select = ["ALL"]
ignore = [
"A", # Shaddowing is fine
]
Ruff also supports monorepos with different rules through hierarchical and cascading configurations.
See also
Integration¶
Jupyter Notebooks¶
Ruff supports linting and formatting Jupyter Notebooks with nbQA. With jupyter-ruff, you can also use Ruff in your notebooks.
IDE¶
Integration with other editors such as Visual Studio Code, PyCharm or Vim is also possible. For the configuration, take a look at Setup.
pre-commit¶
Ruff can be used as a pre-commit hook via ruff-pre-commit:
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.12.10
hooks:
- id: ruff-check
args: [--fix, --exit-non-zero-on-fix]
exclude: docs
- id: ruff-format