66

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
Reez0
  • 2,512
  • 2
  • 17
  • 39

10 Answers10

19

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?

sinapan
  • 948
  • 1
  • 9
  • 23
  • 1
    you can try using `--enable= W0611` instead. For a list of options you can refer to: https://docs.pylint.org/en/1.6.0/features.html – sinapan Apr 03 '19 at 18:31
  • 7
    If you're curious where the User Settings are you can press `CMD/CTRL + SHIFT + P` and then type "settings.json" to bring it up. – Josh Correia Nov 22 '19 at 14:59
  • 4
    Does it remove the code automatically? But it's not working for me. – Ggicci Dec 11 '19 at 06:42
  • 17
    Pylint doesn't edit your code. This command will just highlight your unused imports. (For me, it doesn't highlight the individual ones, just the line start, which is less than ideal) – Dave Feb 14 '20 at 00:19
  • 3
    @Dave: For me its the same. An import like from `django.utils import timezone` is not marked, only import like `import datetime`. Is there a way to fix this? – user1383029 Apr 03 '20 at 08:08
  • @sinapan This doesn't remove any imports, or answer the OP's question. – MEMark Sep 10 '22 at 15:45
17

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..?

danwild
  • 1,886
  • 1
  • 26
  • 31
11

The autoflake vscode extension removes unused imports (rather than just highlighting them or sorting them).

What to do:

  1. Install the autoflake python package e.g. via pip install autoflake (this will be used by the extension).
  2. Install the autoflake vscode extension via the extensions tab in vscode.
  3. (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"
            },
        ]
    },
}
teichert
  • 3,963
  • 1
  • 31
  • 37
  • 4
    Thanks for showing me Save and Run. But once you've installed from PyPI you don't need the VSCode extension; you can just put `"cmd": "autoflake -i --remove-all-unused-imports --remove-unused-variables ${file}"` (or whatever options you want). Note the ability to [inline `# noqa`](https://github.com/myint/autoflake#excluding-specific-lines) to exclude specific import auto-removals. – Nathaniel Jones Dec 03 '21 at 07:22
  • 2
    @NathanielJones Thanks; nice point! One nice thing about that is that using autoflake directly gives extra flexibility on using the package. For those interested in using that method, note that it requires (1) changing the name of the setting to `"saveAndRun"` (vs `"saveAndRunExt"`), (2) dropping the `"isShellCommand"` option, and (3) using `"cmd"` to call autoflake. However, so far I actually prefer the `autoflake` extension because it doesn't pollute my terminal and terminal history with the command (when I used the `"saveAndRun"` as proposed, the commands were run in my active terminal). – teichert Dec 04 '21 at 04:48
  • 1
    That sounds nice to not have the terminal clutter. But where are you getting `"saveAndRunExt"`? In the link you share in your answer, the example shows just `"saveAndRun"`. When I add "Ext", my VSCode says, "Unknown Configuration Setting". – Nathaniel Jones Dec 07 '21 at 00:45
  • 1
    @NathanielJones Great catch! I actually had two separate extensions installed (the Ext version was a fork from the one I originally had which I had a link to). I've now fixed my answer to use the extension I'm actually using which is now consistent with the setting snippet. Thanks again! (and please do ask again if it doesn't work as advertised :) – teichert Dec 08 '21 at 00:21
9

You can create such a VSCode Task by yourself.

1. Install autoflake

pip install autoflake

2. Create Vscode Task

  • Create ".vscode/tasks.json".

  • Add the following settings.

Option 1. Without 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": []
        },
    ]
}

Option 2. With 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.

PowerShell

"command": "${command:python.interpreterPath}\\..\\activate.ps1\r\n",
"args": [
    "autoflake",
    "--in-place",
    "--remove-all-unused-imports",
    "${file}", 
],

Command Prompt

"command": "${command:python.interpreterPath}\\..\\activate &&",
"args": [
    "autoflake",
    "--in-place",
    "--remove-all-unused-imports",
    "${file}", 
],

Bash

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}\"", 
],

3. Add the task to keyboard shortcuts (Optional)

  • Press CtrlShiftP 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.

Unfortunately, vscode-autoflake did not work in to my environment for some reason.

mikm
  • 111
  • 1
  • 4
  • Would be nice to have a cross-platform solution though unless Activate.ps1 (powershell is somewhat available in OSX and Linux) – Bruno Jun 30 '22 at 13:13
  • It might work on linux and osx if you remove ".ps1". Also, although it is not generally true, but for autoflake, "${command:python.interpreterPath} -m autoflake..." seems to work fine even if you are using venv. – mikm Jun 30 '22 at 17:05
9

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": true,
          "source.unusedImports": true
        }
    }
Tulio Casagrande
  • 1,499
  • 1
  • 15
  • 20
emv
  • 101
  • 1
  • 4
  • I could not get it to work with your command, but instead using `"command": "editor.action.fixAll"` (and no args). One needs to define also the settings `"python.analysis.fixAll" : ["source.unusedImports"]`. See also post below. – Joschua Jun 21 '23 at 15:43
  • Have you got the latest update of Pylance? I note that there were a few versions ( v2023.5.20 < v < v2023.5.50) where this was broken, but the latest version has fixed (for me at least), see [github issue](https://github.com/microsoft/pylance-release/issues/4464). From memory the `fixAll` source action for unused imports was superseded by what I have written above, so maybe you have an older pylance version? – emv Jun 23 '23 at 08:57
6

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/

HadiAlqattan
  • 413
  • 5
  • 13
6

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!

ruhanbidart
  • 4,564
  • 1
  • 26
  • 13
4
  • 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

carlsborg
  • 2,628
  • 19
  • 21
  • `"source.unusedImports": true,` helped me to delete unused imports, thx – Anton Danilchenko May 10 '23 at 18:40
  • If one wants to run this action on a specific keyboard command, you need the `"command": "editor.action.fixAll"` in addition to the settings above. Took me a moment to find it, and I think it is useful to mention here. (I would write the full entry from the `keybindings.json` in here, but comments do not allow multi-line code. I think it is easy to figure out after opening the file) – Joschua Jun 21 '23 at 15:33
1

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.)

mikm
  • 111
  • 1
  • 4
0

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).

RobC
  • 22,977
  • 20
  • 73
  • 80
Brendan
  • 1,905
  • 2
  • 19
  • 25