How to autoremove dependent Python packages within a pipenv when uninstalling a package?

Viewed 3214

When you use pipenv to install a package, all the dependent packages will also be installed with it. Uninstalling that package with pipenv uninstall will not remove the dependent packages automatically.

How to get the equivalent functionality of pip-autoremove within a pipenv?

For example:

$ cd testpipenv
$ pipenv install requests
$ pipenv shell
(testpipenv) $ pipenv graph

requests==2.24.0
 - certifi [required: >=2017.4.17, installed: 2020.6.20]
 - chardet [required: >=3.0.2,<4, installed: 3.0.4]
 - idna [required: >=2.5,<3, installed: 2.10]
 - urllib3 [required: >=1.21.1,<1.26,!=1.25.1,!=1.25.0, installed: 1.25.9]

(testpipenv) $ pipenv uninstall requests
(testpipenv) $ pip list

Package    Version
---------- ---------
certifi    2020.6.20
chardet    3.0.4
idna       2.10
pip        20.1.1
setuptools 47.3.1
urllib3    1.25.9
wheel      0.34.2

The dependent packages of requests, such as urllib3 are still installed which can be verified by

(testpipenv) $ python 
>>> import urllib3

This was also discussed here: Pipenv uninstall doesn't uninstall dependencies - issue #1470, and I have not found a more current set of instructions in regards to autoremoval of packages with pipenv.

Versions used:

  • pipenv, version 2020.5.28
  • Python 3.6.10
1 Answers

TL;DR

(testpipenv) $ pipenv uninstall requests && pipenv clean

To get similar functionality to pip-autoremove using just pipenvcommands I did the following, continuing with the example above:

(testpipenv) $ pipenv graph
 
certifi==2020.6.20
chardet==3.0.4
idna==2.10
urllib3==1.25.9

This shows that the dependent packages are still installed, but these have already been removed form Pipfile.lock. Therefore, using pipenv clean will remove them:

(testpipenv) $ pipenv clean

Uninstalling certifi…
Uninstalling idna…
Uninstalling urllib3…
Uninstalling chardet…

In summary...

(testpipenv) $ pipenv uninstall requests && pipenv clean

... will remove all the dependent packages and is the closest equivalent to pip-autoremove.

This may be more aggressive than intended as the clean command 'Uninstalls all packages not specified in Pipfile.lock' If packages have not been added to Pipfile.lock before using clean, this command might remove more than intended. I do not know if this is really a concern, as uninstall automatically updates Pipfile.lock unless additional options such as --skip-lock are specified.


Another alternative would be...

pipenv --rm && pipenv install

... which will remove everything and rebuild the virtual environment based on Pipfile.lock. This would work but is slow as it deletes the full virtual environment and reinstalls everything, except for the unneeded dependencies.

Related