46

When installing my python package, I want to be able to tell the user about various optional dependencies. Ideally I would also like to print out a message about these optional requirements and what each of them do.

I haven't seen anything yet in the docs of either pip or docutils. Do tools these support optional dependencies?

Mike Cooper
  • 2,725
  • 2
  • 24
  • 29
  • Possible duplicate of: http://stackoverflow.com/questions/3664478/optional-dependencies-in-a-pip-requirements-file – Gregg Jun 04 '11 at 17:04
  • If they're optional, they're not strictly dependencies, are they? – Vinay Sajip Jun 05 '11 at 12:46
  • 4
    I call them optional dependencies, because that is what ubuntu's package manager call them. They are not strictly required, but if they are installed, the program can use them. – Mike Cooper Jun 05 '11 at 17:19
  • 2
    Not a duplicate of 3664478, the other asker explicitly wanted pip-requirements which isn't a very natural way to handle this. – Tobu Dec 03 '12 at 11:00

2 Answers2

45

These are called extras, here is how to use them in your setup.py.

The base support is in pkg_resources. You need to enable distribute in your setup.py. pip will also understand them:

pip install 'package[extras]'
Luke Taylor
  • 7,267
  • 8
  • 49
  • 82
Tobu
  • 23,953
  • 4
  • 89
  • 98
  • 15
    Is there a standardised way to view which extras are available? – Sean1708 Oct 10 '15 at 12:32
  • 1
    @Sean1708 No, pip doesn't have a feature like that today. One workaround is to inspect the source code's `setup.py` file for extras. Another is to check the "extras" key in the installed package's `-.dist-info/metadata.json` inside `site-packages` (or wherever you have the package installed). – Taylor D. Edmiston Jun 21 '17 at 20:06
  • Updated documentation link: https://setuptools.pypa.io/en/latest/userguide/dependency_management.html#optional-dependencies – Eric Smith Mar 07 '22 at 19:49
15

Yes, at stated by @Tobu and explained here. In your setup.py file you can add a line like this:

extras_require = {
        'full': ['matplotlib', 'tensorflow', 'numpy', 'tikzplotlib']
    }

I have an example of this line here.

Now you can either install via PIP basic/vanilla package like pip install package_name or the package with all the optional dependencies like pip install package_name[full]

Where package_name is the name of your package and full is because we put "full" in the extras_require dictionary but it depends on what you put as a name.


If someone is interested in how to code a library that can work with or without a package I recommend this answer

Agustin Barrachina
  • 2,697
  • 1
  • 26
  • 38