Python ImportError vs. ModuleNotFoundError

Python raises ModuleNotFoundError when a Python module is not able to be found. This exception catches a much narrow range of faults than the parent exception ImportError.

Although we often like to make exception handling more specific, we have found as a practical matter that using ImportError in a try: except: exception handler is almost always the most appropriate choice. This is particularly true for modules like h5py that require compiled-language interfaces. For example, h5py relies on the HDF5 library. We have found a small percentage of systems with conflicting HDF5 library versions on the system path, which causes h5py to raise ImportError. In these cases, we usually wish to detect that the imported module is ready to work, not just whether it is found or not.

Example

For Python imports loading compiled-language modules, the following is generally recommended:

try:
    import h5py
except ImportError as e:
    h5py = None

def myfun():
    if h5py is None:
        raise ImportError(f"myfun() requires h5py, which failed to import with error {e}")
    # rest of myfun()