'Is there a way to remove unused imports for Python in VS Code?
I would really like to know if there is some Extension in Visual Studio Code or other means that could help identify and remove any unused imports.
I have quite a large number of imports like this and it's getting close to 40 lines. I know some of them aren't in use, the problem is removing them safely.
from django.core.mail import EmailMultiAlternatives, send_mail
from django.template.loader import render_to_string
from django.utils.html import strip_tags
from rest_framework import routers, serializers, viewsets, status
from rest_framework.views import APIView
from rest_framework.response import Response
from django.contrib.auth.models import User
Solution 1:[1]
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?
Solution 2:[2]
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..?
Solution 3:[3]
You can create such a VSCode Task by yourself. I came up with this idea after seeing the answers to the question. I posted this answer because autoflake vscode extension
did not work in to my environment for some reason.
1. Install autoflake
pip install autoflake
2. Create Vscode Task
Create ".vscode/tasks.json".
Add the following settings.
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "autoflake.removeUnusedImports",
"command": "${command:python.interpreterPath} -m",//or "${command:python.interpreterPath}\\..\\Activate.ps1\r\n",
"args": [
"autoflake",
"-i",
"--remove-all-unused-imports",
"${file}"
],
"presentation": {
"echo": true,
"reveal": "silent",
"focus": false,
"panel": "dedicated",
"showReuseMessage": false,
"clear": false,
"close": true
},
"problemMatcher": []
},
]
}
3. Add the task to keyboard shortcuts (Optional)
Press Ctrl+Shift+P
and select Preferences: Open Keyboard Shortcuts (JSON)
.
Add the following settings.
[
{
"key": "Shift+Alt+P",//Set this value to any you like.
"command": "workbench.action.tasks.runTask",
"args": "autoflake.removeUnusedImports",
}
]
In this way, pressing the shortcut key will automatically delete unused imports.
Solution 4:[4]
I suggest to add pycln
as a pre-commit hook, it desinged for this task!
(It works only with Python 3.6+).
Docs: https://hadialqattan.github.io/pycln
Solution 5:[5]
For now there is no clear way to do that on VSCode, but you can easily use pycln to do that, just do:
pip3 install pycln
pycln path_of_your_file.py -a
And then all the unused imports are going to be removed!
Solution 6:[6]
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"
},
]
},
}
Solution 7:[7]
I recognize this is a workaround at best, but if you want this functionality, Pycharm and IntelliJ does it automatically with the optimize imports hotkey (ctrl + opt + o on MacOS).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | sinapan |
Solution 2 | danwild |
Solution 3 | |
Solution 4 | HadiAlqattan |
Solution 5 | |
Solution 6 | |
Solution 7 | RobC |