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.
import not_installed # ModuleNotFoundError: No module named 'not_installed' from math import cube # ImportError: cannot import name 'cube' from 'math'
Try it
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.
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
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 PILcomes from thePillowpackage,import yamlfromPyYAML. 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.pyorjson.pyin your folder shadows the standard one, which produces errors such ascannot import name ... from partially initialized module. - Circular imports. When
a.pyimportsb.pyandb.pyimportsa.pywhileais 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 withattempted relative import with no known parent package. Run it withpython -m package.module. - Optional features. Catch
ImportErrorand set a flag or fallback, as in the example. Catch onlyImportError, not a bareexcept, so real bugs are not hidden. - Modules cache in
sys.modules. A secondimportof the same module does not run its code again. To reload during development useimportlib.reload(). - Error inside the module. If a module raises a different exception while it executes (say
ValueErroron its first line), you see that exception, notImportError. - Python version differences. Modules are added and removed over time:
tomllibappeared in 3.11 anddistutilswas removed in 3.12, so an old script may fail withModuleNotFoundErroron a new interpreter. - Test for a module without importing it by using
importlib.util.find_spec(name), which returnsNonewhen it is absent.