Mike Cooper
Mike Cooper

Reputation: 3048

Optional dependencies in distutils / pip

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?

Upvotes: 67

Views: 47453

Answers (3)

Tobu
Tobu

Reputation: 25426

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

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]'

Upvotes: 67

Jake Stevens-Haas
Jake Stevens-Haas

Reputation: 1686

Since PEP-621, this information is better placed in the pyproject.toml rather than setup.py. Here's the relevant specification from PEP 621. Here's an example snippet from a pyproject.toml (credit to @GwynBleidD):

[project.optional-dependencies]
test = [
  "pytest < 5.0.0",
  "pytest-cov[all]"
]
lint = [
  "black",
  "flake8"
]
ci = [
  "pytest < 5.0.0",
  "pytest-cov[all]",
  "black",
  "flake8"
]

A more complete example is found in the PEP

Upvotes: 18

J Agustin Barrachina
J Agustin Barrachina

Reputation: 4090

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

Upvotes: 23

Related Questions