pythonisortruff

Sort imports alphabetically with ruff


Trying ruff for the first time and I'm not being able to sort imports alphabetically, using default settings. According to docs ruff should be very similar to isort.

Here is a short example with unsorted imports

import os
import collections

Run ruff command

$ ruff format file.py
1 file left unchanged

But if I run isort the imports are properly sorted

$ isort file.py 
Fixing .../file.py

What am I doing wrong?


Solution

  • According to https://github.com/astral-sh/ruff/issues/8926#issuecomment-1834048218:

    In Ruff, import sorting and re-categorization is part of the linter, not the formatter. The formatter will re-format imports, but it won't rearrange or regroup them, because the formatter maintains the invariant that it doesn't modify the program's AST (i.e., its semantics and behavior).

    To get isort-like behavior, you'd want to run ruff check --fix with --select I or adding extend-select = ["I"] to your pyproject.toml or ruff.toml.