[Solution] ModuleNotFoundError: No module named ‘…’

There might be several reasons for getting ModuleNotFoundError in Python. This article describes solutions for ModuleNotFoundError. Common causes of ModuleNotFoundError are:

  • Python module is not installed
  • Conflict between package and module names
  • Dependency conflict between Python modules

Python module is not installed

The first thing you should check is whether the Python module is installed. To use a module in your Python program, you should first install it. For instance, if you try to use numpy module without installing it using pip install command, you will get the following error.

Traceback (most recent call last):
   File "", line 1, in 
 ModuleNotFoundError: No module named 'numpy'

To install the required module, you can use the following command:

pip install numpy

or

pip3 install numpy

or, if you are using Anaconda, you can use the following command:

conda install numpy

Please note that there might be multiple Python instances (or virtual environments) installed on your system. Make sure that the required module is installed to the correct Python instance.

Conflict between package and module names

Another cause for ModuleNotFoundError is a conflict between package and module names. Consider you have the following directory structure in your Python project:

demo-project
 └───utils
         __init__.py
         string_utils.py
         utils.py

If you use the following import statement in utils.py file, Python will give ModuleNotFoundError.

import utils.string_utils
Traceback (most recent call last):
   File "C:\demo-project\utils\utils.py", line 1, in 
     import utils.string_utils
 ModuleNotFoundError: No module named 'utils.string_utils';
 'utils' is not a package

In the error message, it tells “utils is not a package”. utils is a package name, but it is also a module name (utils.py). This is the cause of confusion, module name shadows the package name. To resolve the conflict, you can rename the file utils.py to something else.

Dependency conflict between Python modules

Sometimes there might be a conflict between Python modules and this conflict can cause ModuleNotFoundError.

In the error message below, it clearly tells that _numpy_compat.py file in scipy library is trying to import numpy.testing.nosetester module.

Traceback (most recent call last):
   File "C:\Users\admin\PycharmProjects\demo-project\venv\
         Lib\site-packages\scipy\_lib\_numpy_compat.py", line 10, in
     from numpy.testing.nosetester import import_nose
 ModuleNotFoundError: No module named 'numpy.testing.nosetester'

ModuleNotFoundError is thrown because numpy.testing.nosetester module is removed from numpy library in v1.18. To solve this problem, you can update numpy and scipy libraries to their most recent versions.

pip install numpy --upgrade
pip install scipy --upgrade 
SHARE