Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 547
Reez0 Avatar asked Nov 17 '18 14:11

Reez0


People also ask

How do I get rid of unused import in VS code?

As of Visual Studio Code Release 1.22 this comes free without the need of an extension. Shift + Alt + O will take care of you.

How do I remove unused imports in Python?

To remove all unused imports (whether or not they are from the standard library), use the --remove-all-unused-imports option. To remove unused variables, use the --remove-unused-variables option.

How do you delete unused variables in Visual Studio?

You can use ReSharper. It will mark all unused variables and allow you to remove them.


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

like image 123
sinapan Avatar answered Oct 05 '22 18:10

sinapan


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

like image 34
danwild Avatar answered Oct 05 '22 19:10

danwild