简体   繁体   中英

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

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?

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 (Windows)

    {
        "version": "2.0.0",
        "tasks": [
            {
                "type": "shell",
                "label": "autoflake.removeUnusedImports",
                "command": "${command:python.interpreterPath}",
                "args": [
                    "-m"
                    "autoflake",
                    "-i",
                    "--remove-all-unused-imports",
                    "${file}", // to run on all files in the working directory, "--recursive", "."
                ],
                "presentation": {
                    "echo": true,
                    "reveal": "silent",
                    "focus": false,
                    "panel": "dedicated",
                    "showReuseMessage": false,
                    "clear": false,
                    "close": true
                },
                "problemMatcher": []
            },
        ]
    }

Option 2. With activate

The above method works at least on Windows (works in PowerShell and Command Prompt, but not in Git Bash), but may not work on other operating systems or environments. (I don't know because I don't have one. Please edit.) In such a situation, using activate may work.

PowerShell

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

Command Prompt

 "command": "${command:python.interpreterPath}\\..\\activate &&",
 "args": [
    "autoflake",
    "-i",
    "--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",
    "-i",
    "--remove-all-unused-imports",
    "\"${file}\"", 
 ],

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.

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

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/

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, eg:

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

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!

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 (ie 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",
          "source.unusedImports"
        }
    }

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

我承认这充其量只是一种解决方法,但是如果您想要此功能,Pycharm 和 IntelliJ 会使用优化导入热键(MacOS 上的ctrl + opt + o )自动执行此操作。

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

What to do:

  1. Install the autoflake python package eg 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 vscode extension and add these settings to settings.json :
{
    "saveAndRunExt": {
        "commands": [
            {
                "match": ".*\\.py",
                "isShellCommand": false,
                "cmd": "autoflake.removeUnused"
            },
        ]
    },
}

I was so interested in resolving this problem that I ended up creating a VSCode extension. You can now use it.

https://marketplace.visualstudio.com/items?itemName=mikoz.autoflake-extension

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM