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
|
The pip line that provides |
|
Import |
- i2.optional.install_command(module, *, package=None, extra=None, extras=None)[source]¶
The pip line that provides
module.extra(elseextras[module], elseextrasof its top-level package) names the extra ofpackagethat 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:
- i2.optional.optional_import(module, *, package=None, extra=None, extras=None)[source]¶
Import
module, or raise aModuleNotFoundErrorsaying how to install it.- Parameters:
- Return type:
The error’s
nameismodule. A module that is installed but whose own imports fail re-raises that error unchanged.