Is there any automatic Python code checker that would check if a given project is present in requirements.txt
(or pyproject.toml
, or Pipenv's lock file) but never imported, thus unused?
Asked
Active
Viewed 35 times
0

dotz
- 884
- 1
- 8
- 17
-
Not that I know one exists, but it would be quite simple to write on your own. Make a parser read a `requirements.txt`/`pyproject.toml` and then read all `.py` files in the root, check if `import X` or `from X` is found as a string in each files content, X being each module included in the requirements. This would be slow but it's the only way I can imagine it would work. – zeehyt Apr 19 '22 at 20:22
-
@zeehyt Unfortunately it's not quite that simple since the name of a package on PyPI (what you put in `requirements.txt`) isn't necessarily the same as the name of the Python package(s) that package includes. E.g., `scikit-learn` <-> `sklearn`, `Pillow` <-> `PIL`. – Brian61354270 Apr 19 '22 at 20:30
-
@Brian Yeah I see where you're getting at, sorry I don't know either but that would be a fantastic tool – zeehyt Apr 19 '22 at 20:30
-
I don't that this is possible using static analysis. Many packages do dynamic imports of various grades of complexity, and so the only way to find out what is actually imported is to execute the code. – BoarGules Apr 19 '22 at 21:56
-
@Brian I recently tried to develop a tool that identifies unused packages, which is also able to deal with the differences in PyPi package names and the imported module names; see my answer [here](https://stackoverflow.com/a/73685484/8037249) if you are interested. – Florian Nov 16 '22 at 09:03