Sort imports alphabetically with ruff
Asked Answered
C

2

7

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?

Cyna answered 24/1 at 21:12 Comment(1)
I'm not familiar with either ruff or isort. Do you have links?Ermines
L
12

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.

Lid answered 24/1 at 21:22 Comment(2)
Yes, I have added this to tool.ruff.lint section of pyproject.toml file, and while running ruff check --fix config.py produces the required error report config.py:37:1: E402 Module level import not at top of file Found 1 error. it does not automatically resort the imports. How do I make it resort the imports properly just like iSort does?Gallup
@Gallup I don't know, probably you should ask a proper new question including a minimal reproducible example.Lid
D
10

You can sort the imports & format the code by running the following commands (source):

ruff check --select I --fix
ruff format

Note that sorting is done at linting stage, which can be a little surprising. There are discussions to address it. Thus, if you only need to sort the imports, you can skip ruff format command.

Note that the above command is equivalent to running isort with profile = "black". Depending on your expectations you might need to fiddle with ruff configuration options. You can find more information in the docs:

Diaeresis answered 12/5 at 10:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.