Imports are incorrectly sorted and/or formatted | VS Code | Python

Question:

In a few of my beginner projects this strange red line underscoring one or more of my imports keeps appearing almost randomly and I can’t figure out why.
As the module is working perfectly fine it shouldn’t have something to do regarding which Folder I open VS Code in as it can get resolved, so sys.path should also have the right path, as far as I’m concerned.
Sometimes it works when I switch my imports around but often it just underscores a single import or switching them around doesn’t do anything.
Also when I try to let VS Code sort them with isort, nothing happens and nothing had ever happened.

Asked By: fabestah

||

Answers:

As I didn’t want to disable the auto imports like @Ahmet Burak suggested, I tried to uninstall VS Code after hours of searching for solutions, reinstalled it, copied over my settings and it still wasn’t working.
Then I got more and more desperate, so I uninstalled it again on the next day, installed it, copied over my settings and somehow sorting imports with isort is working just fine now even though I have the same settings and setup as before.
I can’t explain what the issue really was but at least it is working.

Edit: After thinking about it, the problem was most likely exactly what @Wesley described in his answer as the problem went away after I had started working on a new project in a new venv. Therefore, my reinstalls where completely pointless and not at all fixing the issue!

Answered By: fabestah

I have had the same issue.

seems to be related to what’s been discussed here
I got around warnings by telling the formatter to ignore the error– i.e. put this in your vscode config :

"python.formatting.autopep8Args": ["--ignore=E402"],
Answered By: Tofusoul

Edit: I realized that recently the isort extension from Microsoft was automatically added to my extensions and this has caused the annoying error to start showing. It may be that the extension is conflicting somehow with the isort library installed in your venv. The extension isn’t needed, so I’ve just disabled it and no longer encounter this error.

It seems like this error started happening after I recently updated my VS Code to 1.73.0 (Insiders). I was able to get around it by splitting up my imports so that they don’t get auto-formatted to be on multiple lines.

Here’s an example:

Before the "fix", notice the squiggly red line with the annoying error:
enter image description here

After the "fix", no more squiggly red line:

enter image description here

Answered By: Wesley Cheek

I disabled the Microsoft isort (2022.2.0) extension and the problem went away. Watch out, there is another isort out there.

Answered By: Bob Denny
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.