Is there a way to remove unused imports for Python in VS Code?
The autoflake vscode extension removes unused imports (rather than just highlighting them or sorting them).
What to do:
- Install the autoflake python package e.g. via
pip install autoflake
(this will be used by the extension). - Install the autoflake vscode extension via the extensions tab in vscode.
- (optional: runs autoflake when you save) Install Save and Run Ext vscode extension and add these settings to
settings.json
:
{
"saveAndRunExt": {
"commands": [
{
"match": ".*\\.py",
"isShellCommand": false,
"cmd": "autoflake.removeUnused"
},
]
},
}
Interestingly, the accepted answer does not address the question - how to remove unused imports.
Pylint does not modify code, it does linting.
Admittedly i still haven't found a great solution for python, but here's what I've seen:
1.
As noted in this answer, VSCode has a basic builtin option to auto-organise imports, didn't work that well for me - your mileage may vary:
option + Shift + O for Mac
Alt + Shift + O
If this does the trick for you, you can also do it on save in VSCodes settings using:
"editor.codeActionsOnSave": {
"source.organizeImports": true
}
2.
A module called autoflake can do this, e.g:
autoflake --in-place --remove-unused-variables example.py
But again, mileage may vary..
Note
I saw an issue logged in the vscode github noting that the "quick fix" functionality is broken, and the vscode team indicated it was an issue with the vscode python plugin.. might be fixed soon..?
Go to the User Settings json file and add the following:
"python.linting.pylintEnabled": true,
"python.linting.pylintArgs": [
"--enable=W0614"
]
This should remove the unused python imports automatically.
More suggestions here: How can I check for unused import in many Python files?