VSCode: how to config 'Organize imports' for Python (isort)

Question:

Mirror question to

I want to configure how VSCode is invoking isort, so I can customize when calling Organize imports in a .py file.


In particular, VSCode has started removing a blank line between two isort-sections, don’t know why.

from django...
from myproject... # removing blanck line between 2 sections
Asked By: Manu Artero

||

Answers:

In VS Code, the "Python" extension provides us with the following settings, which can merge specific imports from the same module into a single import statement, and organize the import statements in alphabetical order. (in "settings.json" file)

"python.sortImports.args": ["-rc", "--atomic"],

For using "Sort Imports" in VS Code, please refer to this document: Sort Imports in VS Code.

Answered By: Jill Cheng

See my answer in
How to find which isort is vscode exactly using
where I describe the steps to see what is actually happening. You will see the command along with the arguments. The version of isort that is built in to the Microsoft Python plugin doesn’t show as isort. Instead it is sortImports.py. It has the path so you can go look at the code for more information.

Answered By: julie

You can make isort compatible with black and enjoy a formatted code upon saving your document. Here are two ways to achieve this:

  1. You can configure Black and Isort’s settings on pyproject.toml.
    Inside your root’s project folder, create/update your pyproject.toml file:
[tool.isort]
multi_line_output = 3
include_trailing_comma = true
force_grid_wrap = 0
line_length = 88
profile = "black"
  1. Edit settings.json and configure Black and Isort.
{
   "[python]": {
    "editor.codeActionsOnSave": {
      "source.organizeImports": true
       }
     },

   "python.formatting.provider": "black",
   "python.sortImports.args": ["--profile", "black"],
}

source.organizeImports: true runs Isort automatically upon saving your document.

Answered By: xshapira

As of the end of 2022, the python.sortImports setting from the vscode-python will be removed. See link.

VS Code wants us to use isort.args from the vscode-isort instead. For example, the common configuration

   "python.sortImports.args": ["--profile", "black"],

should be replaced with

   "isort.args": ["--profile", "black"],

Otherwise you will see the

"This setting will be removed soon. Use isort.args instead."

message.

Answered By: Pawel Kam
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.