Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$ 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading