In python projects, we always need a linter to catch potential issues and enforce best practices. In the past, there were linters like pylint, flake8. However, they are not performant for large code bases and also you have to install different tools for linting.
Then ruff came out in 2022 and completely changed the Python linter landscape. It can literally replace all the other major linters with comprehensive support of different rules. See here for the download trends on ruff, pylint and flake8.
How to use?#
Follow the official guide to install ruff, then use it like this:
uv run ruff check path/to/srcRuff also provides fixes for some of the linting errors with --fix option:
uv run ruff check --fix path/to/srcConfiguration#
Ruff supports pyproject.toml, ruff.toml or .ruff.toml as configuration file.
If you want to configure different tools in one file, just pick pyproject.toml.
This is a basic configuration for ruff:
[tool.ruff]
# disable preview rules, see https://docs.astral.sh/ruff/preview/
preview = false
line-length = 100
# the python version of the project
target-version = "py313"
[tool.ruff.lint]
select = ["ALL"]
ignore = [
"PTH",
"D407", "D406",
]
[tool.ruff.lint.per-file-ignores]
# ignore rule based on file patterns
"tests/**/*" = [
"ARG001",
"PTH",
]In the above config, we use an inverse strategy for rule selection: we select all the supported rules and ignore the rules we do not want. This way, you can catch as many issues as possible.
For the complete set of rules, see ruff rules.
Use fine-grained rules#
In some cases, you want to enforce a rule, but want to ignore it in certain line, block or file. You can use comments to ignore certain ruff rules.
Ruff formatting?#
Ruff can also act as the formatter, like the well-known [black][https://github.com/psf/black] formatter.
uv run ruff format src/
# like black, you can also run ruff format in check mode, which emits a non-zero status when there
# are un-formatted files.
uv run ruff format --check src/They are pretty similar in terms of format output. If you want to stick to black for formatting, that is also fine: ruff linting can also work together with black perfectly.
Integration to IDE#
Ruff also supports Language Server Protocol and can be integrated into various editors. For neovim, you can use the ruff config from [nvim-lspconfig][nvim-lspconfig-github] and then enable the server:
vim.lsp.enable("ruff")If you want to the customize the ruff LSP server, create file ~/.config/nvim/after/lsp/ruff.lua in your nvim config,
with the following config:
---@type vim.lsp.Config
return {
init_options = {
-- the settings can be found here: https://docs.astral.sh/ruff/editors/settings/
settings = {
organizeImports = true,
},
},
}