uf.optional#
Import optional dependencies without masking broken installs.
A bare except ImportError around import pandas also swallows the
ImportError of a pandas that is installed but fails to import (a missing
dependency of pandas, an incompatible binary). The feature then silently turns itself
off. import_optional tolerates only the absence of the named package itself.
Functions
|
Return the imported module, or |
- uf.optional.import_optional(module_name, *, absent=None)[source]#
Return the imported module, or
Noneif the optional package is not installed.Only a
ModuleNotFoundErrornaming the package itself (the first segment ofmodule_name, or one ofabsent) counts as “not installed”. Every other failure – a missing submodule, a missing dependency of the package, a broken import inside it – is a broken environment and propagates. A namespace package (a bare directory of that name onsys.path, with no__init__.py) is not the package either, so it counts as not installed – which also means a package that is legitimately a namespace package (google) can’t be imported with this.- Return type:
>>> import_optional('json').__name__ 'json' >>> import_optional('_uf_no_such_package_') is None True >>> import_optional('json.no_such_submodule') Traceback (most recent call last): ... ModuleNotFoundError: No module named 'json.no_such_submodule'