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

Solution 1:

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

Solution 2:

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

Solution 3:

You can also consider vulture as one of several options.

Installation

pip install vulture  # from PyPI

Usage

vulture myscript.py

For all python files under your project.

find . -name "*.py" | xargs vulture | grep "unused import"

Example

Applies to the code below.

import numpy as np
import pandas as pd

df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})

The results are as follows.

➜ vulture myscript.py
myscript.py:1: unused import 'np' (90% confidence)
myscript.py:4: unused variable 'df' (60% confidence)

Solution 4:

Have a look at PyChecker. It is a debugging tool and able to find unused variables and modules.

Solution 5:

I have been using pyflakes successfully and wished to auto-remove the unused imports.

I recently found autoflake:

  • Uses pyflakes for checking.
  • Defaults to removing unused standard library imports and redundant pass statements.
  • Has options for removing other unused imports and unused variables.