Reputation: 2689
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
Upvotes: 79
Views: 74929
Reputation: 106
If you are looking for the solution in later version of VS Code (mine is 1.93.1), you would need to do 2 things:
"editor.codeActionsOnSave": {
"source.organizeImports": "always",
"source.unusedImports": "always"
}
Note: I would recommend to update the setting for python files only by using the following syntax:
"[python]": {
"editor.codeActionsOnSave": {
"source.organizeImports": "always",
"source.unusedImports": "always"
}
}
Upvotes: 0
Reputation: 503
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",
}
}
Upvotes: 39
Reputation: 2939
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.
"editor.codeActionsOnSave": {
"source.unusedImports": true,
}
you can also add "source.organizeImports": true in there to sort imports on save.
"python.languageServer": "Pylance",
Docs here
Upvotes: 26
Reputation: 160
With this recently created VSCode extension, autoflake runs automatically by clicking on the context menu of the Explorer (in VSCode) tab or invoking a command from the command palette to remove unused imports.
https://marketplace.visualstudio.com/items?itemName=mikoz.autoflake-extension
(As my previous answer was somehow deleted by a moderator, I'm posting a new one lol.)
Upvotes: 1
Reputation: 160
You can create such a VSCode Task by yourself.
pip install autoflake
Create ".vscode/tasks.json".
Add the following settings.
activate
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "autoflake.removeUnusedImports",
"command": "${command:python.interpreterPath}",
// in Git Bash, "'${command:python.interpreterPath}'",
"args": [
"-m"
"autoflake",
"--in-place",
"--remove-all-unused-imports",
"${file}",
// in Git Bash, "'${file}'",
// to run on all files in the working directory, replace "${file}", with "--recursive", "."
],
"presentation": {
"echo": true,
"reveal": "silent",
"focus": false,
"panel": "dedicated",
"showReuseMessage": false,
"clear": false,
"close": true
},
"problemMatcher": []
},
]
}
activate
The above method (running autoflake as a module) works at least on Windows (works in PowerShell and Command Prompt, Git Bash), and may work on other operating systems or environments. (I don't know because I don't have one. Please edit.) Alternatively, you can use activate
.
"command": "${command:python.interpreterPath}\\..\\activate.ps1\r\n",
"args": [
"autoflake",
"--in-place",
"--remove-all-unused-imports",
"${file}",
],
"command": "${command:python.interpreterPath}\\..\\activate &&",
"args": [
"autoflake",
"--in-place",
"--remove-all-unused-imports",
"${file}",
],
In Bash, it seems that file paths must be enclosed in quotation marks.
"command": "source",
"args": [
"\"${command:python.interpreterPath}\\..\\activate\"\r\n"
"autoflake",
"--in-place",
"--remove-all-unused-imports",
"\"${file}\"",
],
Preferences: Open Keyboard Shortcuts (JSON)
.[
{
"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.
Unfortunately, vscode-autoflake
did not work in to my environment for some reason.
Upvotes: 10
Reputation: 4713
The autoflake vscode extension removes unused imports (rather than just highlighting them or sorting them).
pip install autoflake
(this will be used by the extension).settings.json
:{
"saveAndRunExt": {
"commands": [
{
"match": ".*\\.py",
"isShellCommand": false,
"cmd": "autoflake.removeUnused"
},
]
},
}
Upvotes: 12
Reputation: 2075
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).
Upvotes: -1
Reputation: 4844
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!
Upvotes: 6
Reputation: 2046
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:
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
}
A module called autoflake can do this, e.g:
autoflake --in-place --remove-unused-variables example.py
But again, mileage may vary..
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..?
Upvotes: 21
Reputation: 501
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
Repo: https://github.com/hadialqattan/pycln
PyPI: https://pypi.org/project/pycln/
Upvotes: 6
Reputation: 1000
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?
Upvotes: 17