ModuleNotFoundError
ModuleNotFoundError is a built-in exception that Python raises when an import statement fails to find a specified module.
This exception is a subclass of ImportError, which lets you catch the specific case of a module that can’t be located, separately from other import failures.
You might run into this exception if you try to import a module that isn’t installed or is otherwise unavailable in your current Python environment.
ModuleNotFoundError Occurs When
- Importing a module that isn’t installed in your Python environment
- Trying to load a custom module that isn’t located in your project’s directory or on Python’s import path
- Importing a module whose entry in
sys.moduleshas been set toNone, which deliberately blocks the import
ModuleNotFoundError Examples
An example of when this exception appears:
>>> import non_existing_module
Traceback (most recent call last):
...
ModuleNotFoundError: No module named 'non_existing_module'
An example of how to handle the exception:
>>> try:
... import non_existing_module
... except ModuleNotFoundError:
... print("The module isn't installed. Please install it to proceed.")
...
The module isn't installed. Please install it to proceed.
You typically don’t raise ModuleNotFoundError manually.
Related Resources
Tutorial
Python import: Advanced Techniques and Tips
The Python import system is as powerful as it is useful. In this in-depth tutorial, you'll learn how to harness this power to improve the structure and maintainability of your code.
For additional information on related topics, take a look at the following resources:
- Absolute vs Relative Imports in Python (Course)
- Python's Built-in Exceptions: A Walkthrough With Examples (Tutorial)
- Python Exceptions: An Introduction (Tutorial)
- Advanced Python import Techniques (Course)
- Python import: Advanced Techniques and Tips (Quiz)
- Working With Python's Built-in Exceptions (Course)
- Python's Built-in Exceptions: A Walkthrough With Examples (Quiz)
- Introduction to Python Exceptions (Course)
- Raising and Handling Python Exceptions (Course)
- Python Exceptions: An Introduction (Quiz)
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.