Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Exceptions

Python ImportError and ModuleNotFoundError

Reference for Python ImportError and ModuleNotFoundError: causes, the name and path fields, circular imports, shadowed modules and optional-dependency patterns.

ImportError is raised when an import statement cannot finish. Two situations produce it: the module was found but the name you asked for does not exist inside it (from math import cube), or the import machinery failed for another reason.

ModuleNotFoundError is a subclass of ImportError raised when the module itself cannot be located: No module named 'requests'. Catching ImportError therefore handles both.

Python
import not_installed          # ModuleNotFoundError: No module named 'not_installed'
from math import cube         # ImportError: cannot import name 'cube' from 'math'

Try it

Python The two kinds of import failure

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Optional dependencies and fallbacks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
try:
    import optional_package
except ImportError as error:
    print(error.name, error.path)
Name Description
name The module that was being imported.
path The file path of the module, if known. It is set mainly when a name could not be imported from a module that was found.
msg The message text.

Raises when: a module cannot be found (ModuleNotFoundError), a name cannot be imported from a module, or a module's code fails while being imported in a way that is reported as an import failure.

Usage notes

  • Install the right package. The import name often differs from the install name: import PIL comes from the Pillow package, import yaml from PyYAML. Check that the interpreter running your code is the one you installed into (see virtual environments).
  • Do not name your file like a module. A script called random.py or json.py in your folder shadows the standard one, which produces errors such as cannot import name ... from partially initialized module.
  • Circular imports. When a.py imports b.py and b.py imports a.py while a is still loading, a name may not exist yet. Fix by moving the shared code to a third module, or by importing inside the function that needs it.
  • Relative imports (from . import helper) work only inside a package; running such a file directly as a script fails with attempted relative import with no known parent package. Run it with python -m package.module.
  • Optional features. Catch ImportError and set a flag or fallback, as in the example. Catch only ImportError, not a bare except, so real bugs are not hidden.
  • Modules cache in sys.modules. A second import of the same module does not run its code again. To reload during development use importlib.reload().
  • Error inside the module. If a module raises a different exception while it executes (say ValueError on its first line), you see that exception, not ImportError.
  • Python version differences. Modules are added and removed over time: tomllib appeared in 3.11 and distutils was removed in 3.12, so an old script may fail with ModuleNotFoundError on a new interpreter.
  • Test for a module without importing it by using importlib.util.find_spec(name), which returns None when it is absent.