i2.optional

Optional dependencies: import a module that an extra provides, and when it is missing say which extra to install.

A package keeps heavy or rarely used dependencies out of its install requirements and lists them under [project.optional-dependencies]. The code that needs one imports it where it uses it, with optional_import(), so that a bare install still imports and the failure, when it comes, names the pip line that fixes it. Bind the package’s own name and its module-to-extra map once:

>>> from functools import partial
>>> my_import = partial(optional_import, package="mypkg", extras={"torch": "local"})
>>> my_import("math").pi
3.141592653589793
>>> my_import("torch_nope")
Traceback (most recent call last):
  ...
ModuleNotFoundError: This needs torch_nope: pip install torch_nope
>>> optional_import("torch_nope", package="mypkg", extra="local")
Traceback (most recent call last):
  ...
ModuleNotFoundError: This needs torch_nope: pip install 'mypkg[local]'

Absent and broken are different failures. A module that is installed but fails on one of its own imports raises that error unchanged: telling the user to install what they already have sends them to pip, which reports success and changes nothing.

Functions

install_command(module, *[, package, extra, ...])

The pip line that provides module.

optional_import(module, *[, package, extra, ...])

Import module, or raise a ModuleNotFoundError saying how to install it.

i2.optional.install_command(module, *, package=None, extra=None, extras=None)[source]

The pip line that provides module.

extra (else extras[module], else extras of its top-level package) names the extra of package that does; without one, the module’s own name.

>>> install_command("torch", package="mypkg", extras={"torch": "local"})
"pip install 'mypkg[local]'"
>>> install_command("torch.nn", package="mypkg", extras={"torch": "local"})
"pip install 'mypkg[local]'"
>>> install_command("PIL")
'pip install PIL'
Return type:

str

i2.optional.optional_import(module, *, package=None, extra=None, extras=None)[source]

Import module, or raise a ModuleNotFoundError saying how to install it.

Parameters:
  • module (str) – The (dotted) module to import.

  • package (str | None) – The distribution whose extra provides it (for the pip line).

  • extra (str | None) – That extra’s name.

  • extras (Mapping[str, str] | None) – A module-to-extra map, for a package that binds it once (functools.partial) and imports many modules.

Return type:

ModuleType

The error’s name is module. A module that is installed but whose own imports fail re-raises that error unchanged.