This is available now with a new release of the pylance extension (which I assume most people using python in VS Code will have).
It should be noted that the optimizeImports with the ctrl + alt/option + o keybinding only sorts and does not remove unused imports (see github issue).
I have autosave in place, so I prefer a keyboard shortcut. If you have the pylance extension, you can add the following to your keybindings.json
{
"key": "shift+alt+r",
"command": "editor.action.codeAction",
"args": {
"kind": "source.unusedImports",
}
}
You can change the key binding to be whatever you want, but basically when you press the keybinding (i.e shift + option/alt + r) it should remove all your unused imports.
I believe if you wanted this automatically on save as above you could add the following into your settings.json:
"[python]": {
"editor.codeActionsOnSave": {
"source.organizeImports": "explicit",
"source.unusedImports": "explicit",
}
}
Answer from emv on Stack Overflowpython - VSCode: Sort imports vs. Organize Imports - Stack Overflow
Python & VS Code: make Black and organize imports work together on save
Python organize imports completely missing?
Remove unused imports on Organize Imports
Videos
This is available now with a new release of the pylance extension (which I assume most people using python in VS Code will have).
It should be noted that the optimizeImports with the ctrl + alt/option + o keybinding only sorts and does not remove unused imports (see github issue).
I have autosave in place, so I prefer a keyboard shortcut. If you have the pylance extension, you can add the following to your keybindings.json
{
"key": "shift+alt+r",
"command": "editor.action.codeAction",
"args": {
"kind": "source.unusedImports",
}
}
You can change the key binding to be whatever you want, but basically when you press the keybinding (i.e shift + option/alt + r) it should remove all your unused imports.
I believe if you wanted this automatically on save as above you could add the following into your settings.json:
"[python]": {
"editor.codeActionsOnSave": {
"source.organizeImports": "explicit",
"source.unusedImports": "explicit",
}
}
Confirm you have Pylance enabled in extensions. It comes with the vscode Python extension by Microsoft.
In your .vscode/settings.json, add this
"python.analysis.fixAll" : ["source.unusedImports"]
Now when you do Ctrl+Shift+P (Comand Palette) -> "Fix All" this will clean up the unused imports.
- To auto cleanup on save, add this:
"editor.codeActionsOnSave": {
"source.unusedImports": true,
}
you can also add "source.organizeImports": true in there to sort imports on save.
- If this doesnt work try overriding any other installed language servers with:
"python.languageServer": "Pylance",
Docs here