Why does my code throw "NameError: name 'ModuleNotFoundError' is not defined" error?

Just to clarify the comments: as many said, ModuleNotFoundError is only available in Python 3.6 and later versions, but Python 2 must be used. However the ImportError exception is available in Python 2 and 3, it's just a bit less precise.

Replacing ModuleNotFoundError with ImportError should work.


If you are still on Python 3.5 and run into the problem

    NameError: name 'ModuleNotFoundError' is not defined

for example when running sphinx-build or pipdeptree or from your own code, then go to PyPi and download and install the module "importlib-metada", latest version in the "2" series viz 2.1.0.

The versions 1 and 2 series of importlib-metadata include a "compat.py" file which provides the missing 'ModuleNotFoundError' functionality.

Do not use the newer/higher 3 series versions because these are for python version 3.6 or higher, and thus no longer includes the ModuleNotFoundError code in the "compat.py" file.

Tags:

Python