Small package that shows how to handle optional imports in python.
https://colab.research.google.com/github/kevinsawade/optional_imports/blob/main/examples.ipynb
$ pip install optional-importsor, if you are working with virtual environments.
$ pip install --user optional-importsThis package contains only a single file which can be used as a standalone. You can download the file with wget and put it into your project.
$ wget https://raw.githubusercontent.com/kevinsawade/optional_imports/main/opt_imports/optional_imports.pyImport optional packages as such:
from optional_imports import _optional_import
pd = _optional_import('pandas')
plt = _optional_import('matplotlib', 'pyplot')
random_array = _optional_import('numpy', 'random.random')
nonexistent = _optional_import('nonexistent_package')Import will be postoned and an error will be raised if the module is not installed.
>>> try:
... nonexistent.function()
... except ValueError as e:
... print(e)
Install the `nonexistent_package` package to make use of this feature.See the Examples section in _optional_import's docstring for more examples.