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 *
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.
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.
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)
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.
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
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 ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With