24

I am trying Ruff for the first time, and I'm not being able to sort imports alphabetically, using the default settings. According to the documentation, 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

Output:

1 file left unchanged

But if I run isort the imports are properly sorted

isort file.py

Output:

Fixing .../file.py

What am I doing wrong?

0

2 Answers 2

34

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

ruff check --select I --fix
ruff format

Note that sorting is done at the 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 documentation:

Sign up to request clarification or add additional context in comments.

Comments

28

According to ruff format doesn't sort imports, leaves file unchanged #8926:

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.

2 Comments

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?
@ruslaniv I don't know, probably you should ask a proper new question including a minimal reproducible example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.