Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check for unused import in many Python files?

Tags:

python

I remember when I was developing in C++ or Java, the compiler usually complains for unused methods, functions or imports. In my Django project, I have a bunch of Python files which have gone through a number of iterations. Some of those files have a few lines of import statement at the top of the page and some of those imports are not used anymore. Is there a way to locate those unused imports besides eyeballing each one of them in each file?

All my imports are explicit, I don't usually write from blah import *

like image 840
Thierry Lam Avatar asked Mar 29 '10 18:03

Thierry Lam


People also ask

How do I find unused imports in Python?

Importchecker is a commandline utility to find unused imports in Python modules. Its output is “grep-like” (and thus “emacs-friendly”), reporting both the module's filenames and line numbers where names are imported that are not acually used in the module. Importchecker will not modify any of the source files.

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 many import are there in Python?

There are generally three groups: standard library imports (Python's built-in modules) related third party imports (modules that are installed and do not belong to the current application) local application imports (modules that belong to the current application)

How do I know what to import in Python?

You can import all the code from a module by specifying the import keyword followed by the module you want to import. import statements appear at the top of a Python file, beneath any comments that may exist. This is because importing modules or packages at the top of a file makes the structure of your code clearer.


Video Answer


2 Answers

PyFlakes (similar to Lint) will give you this information.

pyflakes python_archive.py  Example output: python_archive.py:1: 'python_archive2.SomeClass' imported but unused 
like image 180
doug Avatar answered Oct 04 '22 15:10

doug


Use a tool like pylint which will signal these code defects (among a lot of others).

Doing these kinds of 'pre-runtime' checks is hard in a language with dynamic typing, but pylint does a terrific job at catching these typos / leftovers from refactoring etc ...

like image 35
ChristopheD Avatar answered Oct 04 '22 16:10

ChristopheD