Sub topic 5
Declaring dependencies and optional extras
This chapter assumes you can read a pyproject.toml file, you know what the [project] table holds, and you have used pip install inside a virtual environment. Here you will declare what your library needs at runtime. You will also add optional extras for features that only some users want.
What a dependency declaration means
A dependency is a distribution on PyPI that your code imports. When you list one in [project].dependencies, the build backend writes it into the built package's metadata as a Requires-Dist line. When someone runs pip install greeter, pip reads those lines and installs the missing packages too.
Each entry is a string in the PEP 508 format. It has a package name, an optional version specifier, and an optional environment marker.
[project]
dependencies = [
"requests>=2.28,<3",
"typing_extensions>=4.5; python_version < '3.11'",
]The first entry accepts any 2.x release from 2.28 upward. The second is installed only on Python versions older than 3.11, because the marker after the semicolon is evaluated on the user's machine at install time.
Choosing version specifiers
A library is installed alongside many other packages, so your specifiers decide whether your users can resolve a working environment. These are the common operators:
| Specifier | Meaning | Typical use |
|---|---|---|
| `>=2.28` | 2.28 or newer | Lower bound, the usual choice |
| `>=2.28,<3` | Newer than 2.28, below the next major version | Guard against known breaking changes |
| `~=2.28` | Same as `>=2.28,<3` | Compatible release shorthand |
| `==2.31.0` | Exactly one version | Avoid in libraries |
| `!=2.30.0` | Exclude one known-bad release | Work around a specific bug |
For libraries, follow these rules:
- Set a lower bound at the oldest version you have tested or know to work. Anything lower is a guess.
- Add an upper bound only when you know a newer major version breaks you. Upper caps you add by default can make two libraries impossible to install together, because each pins a different range of a shared dependency.
- Do not pin exact versions. Exact pins belong in an application's lock file or requirements file, not in library metadata.
The test of whether a lower bound is honest is to install that exact minimum version in a clean environment and run your tests.
Declare every import
A common error is importing a package that you never declared. It works on your machine because the package happens to be installed there, perhaps as a dependency of something else. It fails for users with ModuleNotFoundError.
The clean-environment test from the build chapters catches this. Install your wheel into a fresh virtual environment and run the code. Anything missing shows up immediately.
Declare the packages you import directly. Do not rely on a package arriving indirectly through another dependency, because that dependency can drop it in a later release.
Optional extras
An extra is a named group of optional dependencies. Users opt in with square brackets: pip install "greeter[color]". Use extras for features that need heavy or niche packages, so the base install stays small.
Extend the greeter project with a colored output feature and test tools:
[project]
name = "greeter"
version = "0.2.0"
requires-python = ">=3.9"
dependencies = []
[project.optional-dependencies]
color = ["rich>=13"]
test = ["pytest>=8"]
all = ["greeter[color,test]"]The all extra refers to the package itself. When pip resolves it, it installs greeter with the color and test extras. This keeps one list of packages per extra, so you do not repeat them.
A note on the test extra: this is the pattern from the topic's example project. Many projects now keep development tools in a separate [dependency-groups] table (PEP 735). Groups are never published in the package metadata. An extra is visible to users and installable by them. Choose an extra only if you want users to be able to request it. This tutorial keeps test as an extra to stay consistent with the example project.
Installing extras
pip install "greeter[color]"
pip install "greeter[color,test]"
pip install -e ".[test]"Always quote the argument. In zsh, unquoted square brackets are treated as a glob pattern, and the command fails with no matches found.
The last command is an editable install of the project in the current directory with the test extra. It is the usual way to set up a development environment.
Extra names are normalized, so Color, color, and COLOR all refer to the same extra. Pick lowercase names with hyphens to avoid surprises.
Writing code for an optional dependency
An extra is a promise only about what pip installs. Your code still runs when the extra is missing, so you must handle that case. Import the optional package lazily and fail with a clear message.
# src/greeter/color.py
def colorize(message: str) -> str:
try:
from rich.markup import escape
except ImportError as exc:
raise ImportError(
"Colored output needs the 'color' extra. "
'Install it with: pip install "greeter[color]"'
) from exc
return f"[bold green]{escape(message)}[/bold green]"Do not import rich at the top of greeter/__init__.py. That would make every user need rich, which defeats the point of the extra.
How pip resolves an extra
In the built metadata, extras appear as Provides-Extra: color and as Requires-Dist: rich>=13; extra == "color". You can see these lines by unzipping the wheel and opening the METADATA file in its .dist-info directory, which is a useful check before uploading.
Python version support
requires-python is a dependency declaration too. It tells pip which interpreters the package supports. pip uses it to skip releases that do not support the user's Python and to pick an older compatible release instead.
If your code uses features from 3.9, then >=3.9 is correct. Do not add an upper bound such as <3.13. An upper bound makes the package uninstallable on new Python versions, even when it would work.
Common errors
- Undeclared import. The code works locally and fails after install. Test in a clean environment.
- Overly tight caps.
requests<2.29conflicts with other libraries that need a newer release. Cap only on known breakage. - Exact pins in a library.
==forces users into one version and creates conflicts. - Top-level import of an extra. The base install raises
ImportErroron import. Import lazily. - Misspelled extra name.
pip install "greeter[colour]"warns that the package does not provide that extra and installs the base package only. Check the warning text. - Unquoted brackets in the shell. Quote the requirement.
- Wrong marker syntax. Strings in markers need quotes:
python_version < '3.11', notpython_version < 3.11.
Checking your declarations
After editing, rebuild and inspect the metadata:
python -m build --wheel
unzip -p dist/greeter-0.2.0-py3-none-any.whl "*.dist-info/METADATA" | grep -E "Requires|Provides"You should see one Provides-Extra line per extra and one Requires-Dist line per dependency. If a line is missing, check the TOML table name. A dependency under the wrong table is silently ignored by some tools.
Exercise
Your library fastparse imports numpy only inside a function to_array(), which most users never call. Where should you declare numpy, and how should to_array() behave when numpy is missing?
Show answer
Declare it as an optional extra, for example [project.optional-dependencies] with array = ["numpy>=1.24"], so the base install stays small. Import numpy inside to_array() in a try/except ImportError block and raise an ImportError with a message telling the user to run pip install "fastparse[array]".
Exercise
A teammate writes dependencies = ["requests==2.31.0"] in a library you publish. Give two problems this causes for users and a better specifier.
Show answer
Users cannot install any other package that needs a different requests version, because the exact pin makes the resolver fail. Users also cannot receive security fixes in newer requests releases. A better specifier is a lower bound, such as requests>=2.28, with an upper cap like <3 only if a new major version is known to break the library.