Is there a way to remove unused imports for Python in VS Code?

Viewed 33662

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
8 Answers

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?

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

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

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.

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!

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

Related