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

6

24

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
Hagiographa answered 12/4, 2021 at 13:51 Comment(3)
It seems that this might be helpful: medium.com/@cereblanco/… , you customize by altering the "python.sortImports.args". Another alternative that I am using is the pre-commit with isortCanaille
When tried those, a pop-up appear: "following deprecated CLI flags were used and ignored: -rc!"Hagiographa
I think the recursive option is deprecated since it is done automatically. github.com/PyCQA/isort/issues/1263Canaille
I
8

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.

Intercollegiate answered 13/4, 2021 at 5:55 Comment(2)
do you know which flags to use for the "expected" order (one that doesn't lead to a pylint-wrong-import error)Hagiographa
@Manu -I'm sorry I don't know about this, but you could create a new thread and describe this question in detail to get a better answer.Intercollegiate
P
30

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",
   "isort.args": ["--profile", "black"],
}

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

As of version 1.85, you want to set "source.organizeImports": "explicit" to get the same functionality as the old "true", per the docs.

Presumptuous answered 18/6, 2022 at 8:39 Comment(8)
Hey @Presumptuous do you need any extensions to make VSCode read that config from pyproject.toml file?Ashla
@Ashla You need poetry as your package manager and pip install isort.Presumptuous
Do you need any VSCode extensions for isort to read config from pyproject.toml?Ashla
@Ashla I think this used to work automatically in older versions of VSCode (or the Python extensions), but with the latest release it seems to have stopped working. I've opened an issue here.Weka
Thx. I have a question about that #74331061 And also I am looking at that issue: github.com/microsoft/vscode-isort/issues/71Ashla
Now we need to install ms-python.isortPreceptory
As of version 1.85, you want to set "source.organizeImports": "explicit" to get the same functionality as the old "true", per the docsOssy
To make VSCode read the stuff from my pyproject.toml I needed "isort.args":["--profile", "black", "--settings-file", "pyproject.toml"] in my settings.json.Metempirics
P
22

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.

Perzan answered 19/1, 2023 at 21:34 Comment(2)
If you also want to use black as a formatter, you will additionally need to install ms-python.black-formatter extension, then set your default formater for python to be blackLoren
I needed to add "source.organizeImports": true, otherwise it only checked isort upon save, it did not apply isort. (See #67060148 )Gallican
I
8

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.

Intercollegiate answered 13/4, 2021 at 5:55 Comment(2)
do you know which flags to use for the "expected" order (one that doesn't lead to a pylint-wrong-import error)Hagiographa
@Manu -I'm sorry I don't know about this, but you could create a new thread and describe this question in detail to get a better answer.Intercollegiate
C
5

You can install Isort extension to VSCode as shown below. *I use Anaconda on Windows 11:

enter image description here

Then, set the code below to settings.json. *You can see my answer explaning how to open settings.json:

// "settings.json"

"[python]": {
    "editor.codeActionsOnSave": {
        "source.organizeImports": true
    }
}

This below is my full settings.json with the code above:

// "settings.json"

{
    "python.defaultInterpreterPath": "C:\\Users\\kai\\anaconda3\\python.exe",
    "window.zoomLevel": 3,
    "files.autoSave": "afterDelay",
    "breadcrumbs.enabled": false,
    "[python]": { // Here
        "editor.codeActionsOnSave": {
            "source.organizeImports": true
        }
    }
}
Chenee answered 11/6, 2023 at 22:26 Comment(1)
This is what I needed. I had been trying to install isort into my virtual environment and hadn't realized there was an extension. ThanksThirst
M
0

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.

Monkfish answered 22/3, 2022 at 21:51 Comment(0)
M
0

In my case isort is not sorting the way I'd like to to be sorted. Here's MWE:

import numpy as np
import pandas as pd
import seaborn as sea_bor_nnnn
import matplotlib.pyplot as plt
import torch
import os

after saving the file I get the following output

import os
                            # why is it inserting an empty line here?
import numpy as np
import torch
import pandas as pd
import seaborn as sea_bor_nnnn
import matplotlib.pyplot as plt
                               # here inserts only 1 blank line instead of 2
#actual code goes here
dfdf
dfdfd
ddf

My preferred format would be the following

import os
import torch
import numpy as np
import pandas as pd
import seaborn as sea_bor_nnnn
import matplotlib.pyplot as plt


# actual code goes here

Notice how all imports are sorted according to length without empty lines in between and that actual code starts after 2 empty lines from the module imports.

Any ideas how to achieve that in vscode? Maybe using using isort in combination with autopep8 or flake8 instead of black

Modiste answered 27/3 at 14:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.