packaging.python.org
packaging.python.org copied to clipboard
Should include guidance on how to handle missing optional dependencies / extras at runtime
A common problem for packages with optional dependencies / extras is that the default user experience when these dependencies haven't been installed by the package consumer isn't great: the end user will just get an ordinary ModuleNotFoundError stemming from the first import of a missing module, without a hint that this module is part of an extra or how to fix it.
As a result, authors of packages with optional dependencies often want to introduce custom handling for missing dependencies, such as raising a more helpful exception that includes the name of the extra that is missing in case of libraries, or showing a more helpful message to the end user in case of applications.
I believe it would make a lot of sense to include guidance on how to do this in the Packaging Guide.
One problem is that there doesn't currently seem to be a good good way of doing this until https://github.com/pypa/packaging-problems/issues/317 has been fixed, but a guide showing the various bad ways and pointing to tickets relevant to future improvements is better than users having to piece the information together from 10 different StackOverflow answers and GitHub issues.
I guess the recommendation would be simple and something like this:
try:
import some_library
except ImportError, ModuleNotFoundException:
handle_missing_dependency()
But the handle_missing_dependency can only be case by case.