Detect unused imports in visual studio code for python 3?

Question:

I am subscribing to this issue about warning unused imports for python in visual studio code.

I am not particular about whether it’s squiggle or gray out. But I am not certain if this feature is available based on the discussion or there’s a workaround using a linter.

I am okay either way so long some detection is available.

I am using pylint as linter for now. Would be okay to use other linter so long I can detect unused imports.

And I do not want to auto remove unused imports.

This is what I see despite turning on pylint. I have purposely added an unused import. And I am not seeing any problems in this file.

enter image description here

Asked By: Kim Stacks

||

Answers:

The Python extension for VS Code does not support warning about unused imports in its language server yet. But if you want Pylint to warn you, create a .pylintrc and and turn on the W0611 warning.

Answered By: Brett Cannon

Update/create VSCode user settings

"python.linting.pylintEnabled": true,
"python.linting.pylintArgs": [
    "--enable=W0614"
]

this works for me in Python 3.6.7 / 3.6.8

Answered By: viru

Visual studio code has released a new feature last year in April in 2018 which allow users to change their settings to remove unused imports automatically on save. Personally I have tried to configure both JavaScript and TypeScript and it works great out of box, so I’ll assume it should also work for Python since you can enable/disable by using the language setting, please try updating your setting.json file with the following new changes:

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

Hopefully this could work on your Python project! Good luck!

Answered By: JayKan

It only highlights the unused imports but not automatically removes them.

"python.linting.pylintEnabled": true,
"python.linting.pylintArgs": [
"--enable=W0614"],
"[python]": {
"editor.codeActionsOnSave": {
  "source.organizeImports": true
}},

Version: 1.37.1 (user setup)
Date: 2019-08-15T16:17:55.855Z
Electron: 4.2.7
Chrome: 69.0.3497.128
Node.js: 10.11.0
V8: 6.9.427.31-electron.0
OS: Windows_NT x64 10.0.16299

Answered By: guest-python

you can try this one:

  • install pylance extension
  • user/workSpace setting languageServer
    {
      "python.languageServer": "Pylance"
    }
    
Answered By: Wollens

I’ve installed the autoflake plugin (https://github.com/PyCQA/autoflake) in VSCode, and added the shortcut CTRL + SHIFT + i. Whenever I press CTRL + SHIFT + i, unused imports are removed.

After installing autoflake, you cand find it pressing CTRL+SHIFT+p on VSCode, then typing autoflake. You can then set up the shortcut.

Answered By: Ruben Alves
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.