25

Is it possible to show the reverse dependencies with pip?

I want to know which package needs package foo. And which version of foo is needed by this package.

animuson
  • 53,861
  • 28
  • 137
  • 147
guettli
  • 25,042
  • 81
  • 346
  • 663

4 Answers4

16

To update the answer to current (2019), when pip.get_installed_distributions() does not exist anymore, use pkg_resources (as mentioned in a comments):

import pkg_resources
import sys

def find_reverse_deps(package_name):
    return [
        pkg.project_name for pkg in pkg_resources.WorkingSet()
        if package_name in {req.project_name for req in pkg.requires()}
    ]

if __name__ == '__main__':
    print(find_reverse_deps(sys.argv[1]))
9769953
  • 10,344
  • 3
  • 26
  • 37
14

I found Alexander's answer perfect, except it's hard to copy/paste. Here is the same, ready to paste:

import pip
def rdeps(package_name):
    return [pkg.project_name
            for pkg in pip.get_installed_distributions()
            if package_name in [requirement.project_name
                                for requirement in pkg.requires()]]

rdeps('some-package-name')
duozmo
  • 1,698
  • 5
  • 22
  • 33
Wernight
  • 36,122
  • 25
  • 118
  • 131
  • 6
    For the record, pip does not have a public API. This answer will be invalid by pip 10. Use `pkg_resources` from setuptools instead. – Alex Grönholm Oct 23 '17 at 07:04
  • 1
    Ref for @AlexGrönholm's comment: https://pip.pypa.io/en/stable/user_guide/#using-pip-from-your-program – David P Jun 20 '18 at 04:59
10

This is possible for already installed packages using pip's python API. There is the pip.get_installed_distributions function, which can give you a list of all third party packages currently installed.

# rev_deps.py
import pip
import sys

def find_reverse_deps(package_name):
    return [
        pkg.project_name for pkg in pip.get_installed_distributions()
        if package_name in {req.project_name for req in pkg.requires()}
    ]

if __name__ == '__main__':
    print find_reverse_deps(sys.argv[1])

This script will output the list of packages, that require a specified one:

$python rev_deps.py requests
Alexander Zhukov
  • 4,357
  • 1
  • 20
  • 31
7

One can use the pipdeptree package. To list reverse dependencies of an installed cffi package:

$ pipdeptree -p cffi -r
cffi==1.14.0
  - cryptography==2.9 [requires: cffi>=1.8,!=1.11.3]
    - social-auth-core==3.3.3 [requires: cryptography>=1.4]
      - python-social-auth==0.3.6 [requires: social-auth-core]
      - social-auth-app-django==2.1.0 [requires: social-auth-core>=1.2.0]
x-yuri
  • 16,722
  • 15
  • 114
  • 161