Что означает ошибка ModuleNotFoundError: No module named
Python ругается, что не может найти нужный модуль
Python ругается, что не может найти нужный модуль
Ситуация: мы решили заняться бигдатой и обработать большой массив данных на Python. Чтобы было проще, мы используем уже готовые решения и находим нужный нам код в интернете, например такой:
import numpy as np
x = [2, 3, 4, 5, 6]
nums = np.array([2, 3, 4, 5, 6])
type(nums)
zeros = np.zeros((5, 4))
lin = np.linspace(1, 10, 20)
Копируем, вставляем в редактор кода и запускаем, чтобы разобраться, как что работает. Но вместо обработки данных Python выдаёт ошибку:
❌ModuleNotFoundError: No module named numpy
Странно, но этот код точно правильный: мы его взяли из блога разработчика и, по комментариям, у всех всё работает. Откуда тогда ошибка?
Что это значит: Python пытается подключить библиотеку, которую мы указали, но не может её найти у себя.
Когда встречается: когда библиотеки нет или мы неправильно написали её название.
Что делать с ошибкой ModuleNotFoundError: No module named
Самый простой способ исправить эту ошибку — установить библиотеку, которую мы хотим подключить в проект. Для установки Python-библиотек используют штатную команду pip или pip3, которая работает так: pip install <имя_библиотеки>
. В нашем случае Python говорит, что он не может подключить библиотеку Numpy, поэтому пишем в командной строке такое:
pip install numpy
Это нужно написать не в командной строке Python, а в командной строке операционной системы. Тогда компьютер скачает эту библиотеку, установит, привяжет к Python и будет ругаться на строчку в коде import numpy.
Ещё бывает такое, что библиотека называется иначе, чем указано в команде pip install. Например, для работы с телеграм-ботами нужна библиотека telebot, а для её установки надо написать pip install pytelegrambotapi
. Если попробовать подключить библиотеку с этим же названием, то тоже получим ошибку:
А иногда такая ошибка — это просто невнимательность: пропущенная буква в названии библиотеки или опечатка. Исправляем и работаем дальше.
Вёрстка:
Кирилл Климентьев
В Python может быть несколько причин возникновения ошибки ModuleNotFoundError: No module named ...
:
- Модуль Python не установлен.
- Есть конфликт в названиях пакета и модуля.
- Есть конфликт зависимости модулей Python.
Рассмотрим варианты их решения.
Модуль не установлен
В первую очередь нужно проверить, установлен ли модуль. Для использования модуля в программе его нужно установить. Например, если попробовать использовать numpy без установки с помощью pip install будет следующая ошибка:
Traceback (most recent call last):
File "", line 1, in
ModuleNotFoundError: No module named 'numpy'
Для установки нужного модуля используйте следующую команду:
pip install numpy
# или
pip3 install numpy
Или вот эту если используете Anaconda:
conda install numpy
Учтите, что может быть несколько экземпляров Python (или виртуальных сред) в системе. Модуль нужно устанавливать в определенный экземпляр.
Конфликт имен библиотеки и модуля
Еще одна причина ошибки No module named — конфликт в названиях пакета и модуля. Предположим, есть следующая структура проекта Python:
demo-project
└───utils
__init__.py
string_utils.py
utils.py
Если использовать следующую инструкцию импорта файла utils.py, то Python вернет ошибку ModuleNotFoundError
.
>>> import utils.string_utils
Traceback (most recent call last):
File "C:demo-projectutilsutils.py", line 1, in
import utils.string_utils
ModuleNotFoundError: No module named 'utils.string_utils';
'utils' is not a package
В сообщении об ошибке сказано, что «utils is not a package». utils — это имя пакета, но это также и имя модуля. Это приводит к конфликту, когда имя модуля перекрывает имя пакета/библиотеки. Для его разрешения нужно переименовать файл utils.py.
Иногда может существовать конфликт модулей Python, который и приводит к ошибке No module named.
Следующее сообщение явно указывает, что _numpy_compat.py в библиотеке scipy пытается импортировать модуль numpy.testing.nosetester
.
Traceback (most recent call last):
File "C:demo-projectvenv
Libsite-packages
scipy_lib_numpy_compat.py", line 10, in
from numpy.testing.nosetester import import_nose
ModuleNotFoundError: No module named 'numpy.testing.nosetester'
Ошибка ModuleNotFoundError
возникает из-за того, что модуль numpy.testing.nosetester
удален из библиотеки в версии 1.18. Для решения этой проблемы нужно обновить numpy и scipy до последних версий.
pip install numpy --upgrade
pip install scipy --upgrade
When you try to import a module in a Python file, Python tries to resolve this module in several ways. Sometimes, Python throws the ModuleNotFoundError afterward. What does this error mean in Python?
As the name implies, this error occurs when you’re trying to access or use a module that cannot be found. In the case of the title, the «module named Python» cannot be found.
Python here can be any module. Here’s an error when I try to import a numpys
module that cannot be found:
import numpys as np
Here’s what the error looks like:
Here are a few reasons why a module may not be found:
- you do not have the module you tried importing installed on your computer
- you spelled a module incorrectly (which still links back to the previous point, that the misspelled module is not installed)…for example, spelling
numpy
asnumpys
during import - you use an incorrect casing for a module (which still links back to the first point)…for example, spelling
numpy
asNumPy
during import will throw the module not found error as both modules are «not the same» - you are importing a module using the wrong path
How to fix the ModuleNotFoundError in Python
As I mentioned in the previous section, there are a couple of reasons a module may not be found. Here are some solutions.
1. Make sure imported modules are installed
Take for example, numpy
. You use this module in your code in a file called «test.py» like this:
import numpy as np
arr = np.array([1, 2, 3])
print(arr)
If you try to run this code with python test.py
and you get this error:
ModuleNotFoundError: No module named "numpy"
Then it’s most likely possible that the numpy
module is not installed on your device. You can install the module like this:
python -m pip install numpy
When installed, the previous code will work correctly and you get the result printed in your terminal:
[1, 2, 3]
2. Make sure modules are spelled correctly
In some cases, you may have installed the module you need, but trying to use it still throws the ModuleNotFound error. In such cases, it could be that you spelled it incorrectly. Take, for example, this code:
import nompy as np
arr = np.array([1, 2, 3])
print(arr)
Here, you have installed numpy
but running the above code throws this error:
ModuleNotFoundError: No module named "nompy"
This error comes as a result of the misspelled numpy
module as nompy
(with the letter o instead of u). You can fix this error by spelling the module correctly.
3. Make sure modules are in the right casing
Similar to the misspelling issue for module not found errors, it could also be that you are spelling the module correctly, but in the wrong casing. Here’s an example:
import Numpy as np
arr = np.array([1, 2, 3])
print(arr)
For this code, you have numpy
installed but running the above code will throw this error:
ModuleNotFoundError: No module named 'Numpy'
Due to casing differences, numpy
and Numpy
are different modules. You can fix this error by spelling the module in the right casing.
4. Make sure you use the right paths
In Python, you can import modules from other files using absolute or relative paths. For this example, I’ll focus on absolute paths.
When you try to access a module from the wrong path, you will also get the module not found here. Here’s an example:
Let’s say you have a project folder called test. In it, you have two folders demoA and demoB.
demoA has an __init__.py
file (to show it’s a Python package) and a test1.py
module.
demoA also has an __init__.py
file and a test2.py
module.
Here’s the structure:
└── test
├── demoA
├── __init__.py
│ ├── test1.py
└── demoB
├── __init__.py
├── test2.py
Here are the contents of test1.py
:
def hello():
print("hello")
And let’s say you want to use this declared hello
function in test2.py
. The following code will throw a module not found error:
import demoA.test as test1
test1.hello()
This code will throw the following error:
ModuleNotFoundError: No module named 'demoA.test'
The reason for this is that we have used the wrong path to access the test1
module. The right path should be demoA.test1
. When you correct that, the code works:
import demoA.test1 as test1
test1.hello()
# hello
Wrapping up
For resolving an imported module, Python checks places like the inbuilt library, installed modules, and modules in the current project. If it’s unable to resolve that module, it throws the ModuleNotFoundError.
Sometimes you do not have that module installed, so you have to install it. Sometimes it’s a misspelled module, or the naming with the wrong casing, or a wrong path. In this article, I’ve shown four possible ways of fixing this error if you experience it.
I hope you learned from it
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
ModuleNotFoundError: No module named in Python occurs when:
- The name of the module is incorrect
- The path of the module is incorrect
- The Library is not installed
- The module is unsupported
- Python 2 instead of Python 3
In this article, We’ll discuss the reasons and the solutions for the ModuleNotFoundError error.
1. The name of the module is incorrect
The first reason for ModuleNotFoundError: No module named is the module name is incorrect. For example, let’s try to import the os module with double «s» and see what will happen:
>>> import oss
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'oss'
As you can see, we got ModuleNotFoundError: No module named ‘oss.’ To solve the error, make sure that you use the correct module name.
Let’s import the module with the correct name.
>>> import os
>>>
As you can see, the error is solved.
2. The path of the module is incorrect
The Second reason is the path of the local module you want to import is incorrect. for example, let’s see a directory structure
Project structure:
core.py
folder_1
---my_module.py
In this folder, we’ve:
- core.py: is the file that will execute
- folder_1: folder contains my_module.py
Now in core.py, let’s try to import my_module.py
core.py
import my_module #incorrect
Output:
ModuleNotFoundError: No module named 'my_module'
As you can see, we got the error because my_module.py is not in the path that we’ve executed core.py. We need to define the module’s path in the following example to solve the error.
core.py
import folder_1.my_module #correct
Output:
...Program finished with exit code 0
Now we’ve imported m_module successfully.
3. The library is not installed
Also, you can get the ModuleNotFoundError: No module named issue if you are trying to import a library module that is not installed in your virtual environment or computer.
So before importing a library’s module, you need to install it with any package-management system.
For example, let’s try to import the Beautifulsoup4 library that’s not installed in my virtual environment.
>>> from bs4 import BeautifulSoup
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'bs4'
Now, let’s install the library and try to re-import it:
pip install beautifulsoup4
Collecting beautifulsoup4
Using cached https://files.pythonhosted.org/packages/d1/41/e6495bd7d3781cee623ce23ea6ac73282a373088fcd0ddc809a047b18eae/beautifulsoup4-4.9.3-py3-none-any.whl
Requirement already satisfied: soupsieve>1.2; python_version >= "3.0" in /home/py/Desktop/seo_pro/seo_env/lib/python3.6/site-packages (from beautifulsoup4) (1.9.5)
Installing collected packages: beautifulsoup4
Successfully installed beautifulsoup4-4.9.3
Re-importing:
>>> from bs4 import BeautifulSoup
>>>
As you can see, after installing the package, the program is working.
4. The module is unsupported
When a library releases a new update, new modules are added, and others are dropped to support it.
If you try to import a module that is n unsupported by the library, you will get ModuleNotFoundError: No module named.
To ensure the module is supported, go to the package documentation and check if the module is available or not.
5. Python 2 instead of Python 3
As you know, Some Python libraries no longer support Python 2. For that reason, you’ll get the ModuleNotFoundError error if you execute a module that does not support Python 2 with Python 2.
To solve the error:
First, let’s check our python version using these two commands:
python -V
# Python 2.7.18
python3 -V
# Python 3.9.5
In my case, Python 3 is on the python3 command, So I will execute the program using python3. If Python3 is not found on your device, Install Python on Windows, Mac, and Linux.
Conclusion
In conclusion, To solve the ModuleNotFoundError: No module named:
- Ensure the name of the module is incorrect
- Ensure the path of the module is incorrect
- Ensure the Library is installed
- Ensure the module is supported
- Ensure using Python 3
Finally, I hope your problem has been fixed.
I realize this seems like a generic question, but all answers pointed to having two simultanious python
installations — I already uninstalled the other one.
Currently I run my code from PyCharm 2017.1.5 (windows 10) with Python interpreter set as Python 3.6.1 (C:Anaconda3python.exe)
, i.e. I installed Anaconda3, which includes the matplotlib
, and run from PyCharm using the Ananconda3-interpreter.
I’ve checked in Anaconda Navigator that matplotlib 2.0.2
is installed in the environment.
A minimal (non-working) example:
import matplotlib.pyplot as plt
plt.plot(range(10))
plt.show()
Returns the following error:
C:Anaconda3python.exe C:/Users/John/Documents/CPU/master/untitled/main11.py
Traceback (most recent call last):
File "C:/Users/John/Documents/CPU/master/untitled/main11.py", line 1, in <module>
import matplotlib.pyplot as plt
File "C:Anaconda3libsite-packagesmatplotlibpyplot.py", line 29, in <module>
import matplotlib.colorbar
File "C:Anaconda3libsite-packagesmatplotlibcolorbar.py", line 34, in <module>
import matplotlib.collections as collections
File "C:Anaconda3libsite-packagesmatplotlibcollections.py", line 37, in <module>
import matplotlib.lines as mlines
File "C:Anaconda3libsite-packagesmatplotliblines.py", line 28, in <module>
from matplotlib.markers import MarkerStyle
ModuleNotFoundError: No module named 'matplotlib.markers'
Process finished with exit code 1
This ran fine 2 weeks ago, but not now. To my knowledge, I didn’t change or update anything. The module loads correctly, but it seems to be a change in the module content? If so: How did that happen and how can I fix it?
asked Aug 15, 2017 at 13:03
RasmusP_963RasmusP_963
2801 gold badge2 silver badges10 bronze badges
3
In my case, I could fix it by setting PYTHONPATH
to the path to site-packages
folder where the needed packages are located, excluding site-pacages
.
I use a pyenv
virtual environment, whose path is /home/apk/.pyenv/versions/python-3-7-4
. When the environment is activated, pip
installs packages to /home/apk/.pyenv/versions/python-3-7-4/lib/python3.7/site-packages
. Therefore, in terminal, I set:
$ PYTHONPATH=/home/apk/.pyenv/versions/python-3-7-4/lib/python3.7/
The same should be true for Windows installations of python
.
If virtual environmets are used, then one could edit activate
script to set PYTHONPATH
.
After I did it, I checked in a python
shell.
$ python
Python 3.7.4 (default, Feb 5 2020, 17:11:33)
[GCC 5.5.0 20171010] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/home/apk/.pyenv/versions/3.7.4/lib/python37.zip', '/home/apk/.pyenv/versions/3.7.4/lib/python3.7', '/home/apk/.pyenv/versions/3.7.4/lib/python3.7/lib-dynload', '/home/apk/.pyenv/versions/python-3-7-4/lib/python3.7']
>>> sys.executable
'/home/apk/.pyenv/versions/python-3-7-4/bin/python'
Good luck!
References
- https://github.community/t5/Programming-Help-and-Discussion/Python-ModuleNotFoundError-although-module-is-installed-aiohttp/td-p/28525
answered Mar 2, 2020 at 16:44
@ImportanceOfBeingErnest lead me in the right direction. I post my solution here s.t. others may find the answer. The problem was a corrupted disk sector — an unlikely event of chance.
The problem was indeed in the matplotlib
-package itself. Retrospectively, pointers to the issue were that errors in pre-distributed packages should not exist. If they do, external circumstances must have corrupted and the problem is not with the Python-installation itself.
I uninstalled matplotlib
through Anaconda Prompt with conda remove matplotlib
and re-installed with conda install matplotlib
. This gave me this error:
(C:Anaconda3) C:UsersJohn>conda install matplotlib
[...]
ERROR conda.core.link:_execute_actions(337): An error occurred while installing package 'defaults::matplotlib-2.0.2-np112py36_0'.
OSError(22, 'Invalid argument') Attempting to roll back.
OSError(22, 'Invalid argument')
Before @Ernest’s comment, I thought it maybe had to do with non-ASCII in PATH
or similar.
Instead I tried to reinstall Anaconda3 completely, restarted and found that part of the Anaconda3-folder weren’t removed (the one containing the matplotlib
).
Deleting it manually gave a Windows error 0x80070570
. Following this post on ServerFault (the comment to OP) I ran a check and afterwards a repair from Windows Explorer GUI: Right-click on the drive in This PC —> Properties —> Tab Tools —> Check (repair appears if any errors are found).
After some restarts, reinstalling Anaconda3 from scratch and restarting again, I was able to run my project again!
answered Aug 15, 2017 at 15:53
RasmusP_963RasmusP_963
2801 gold badge2 silver badges10 bronze badges
It is difficult to answer this question directly, however, I have seen a large amount of issues in corporate Windows environments with PyCharm and Anaconda these are some of the issues you may be having
-
Check you
PATH
is correctly pointing to all Anaconda locationsimport sys sys.path
-
Check that your files have not been migrated to
C:UsersusernameAppDataRoaming
by your IT team - Purge your system for any
python
distributions. There may be software distributions that you use internally that package their ownpython
distribution. This can often be included in thePATH
. Another example could be installing Anaconda to yourC:
but also having it already installed inUsersLocalAppData
or'C:Program Files'
months before and forgotten!
A good way of directly debugging your problem would be to navigate to the following directory in ipython
C:Anaconda3libsite-packagesmatplotlib
and they try import matplotlib.markers
If this fails then you could then try
import matplotlib
matplotlib.__file__
you should check that this result gives
'C:\Anaconda3\lib\site-packages\matplotlib\__init__.pyc'
as most likely there will be another matplotlib
version installed that is taking precedence. This will then fall under one of the issues above to correct.
answered Aug 15, 2017 at 13:24
2
Got the same type of error while using pip. created new VENV and execute the app agaist that resolved my issue
answered Nov 1, 2020 at 17:06
PyCharm requires installing packages available in the interpreter.
You can find matplotlib and other packages available for an install using the following steps:
- Open the File—Settings—Project—Project Interpreter menu.
- You should see all packages you currently have installed, and matplotlib should be missing from this list.
- Click the + (add) button to the right and install the matplotlib package.
- Once complete, close the top dialog box, and you should see matplotlib in the list of installed packages.
answered Feb 17, 2018 at 2:12
yellowjacket05yellowjacket05
1501 gold badge2 silver badges12 bronze badges
1
Jan 5, 2018 10:00:56 AM |
Python Exception Handling: ImportError and ModuleNotFoundError
A look into the ImportError and ModuleNotFoundError in Python, with code showing how to deal with failed imports in Python 2.7 and 3.6.
Making our way through our detailed Python Exception Handling series we arrive at the ImportError, along with its single child subclass of ModuleNotFoundError. The ImportError
is raised when an import
statement has trouble successfully importing the specified module. Typically, such a problem is due to an invalid or incorrect path, which will raise a ModuleNotFoundError
in Python 3.6 and newer versions.
Within this article we’ll explore the ImportError
and ModuleNotFoundError
in a bit more detail, beginning with where they sit in the overall Python Exception Class Hierarchy. We’ll also take a look at some simple code samples that illustrate the differences in import
statement failures across newer (3.6) and older (2.7) versions of Python, so let’s get started!
The Technical Rundown
All Python exceptions inherit from the BaseException
class, or extend from an inherited class therein. The full exception hierarchy of this error is:
BaseException
Exception
ImportError
ModuleNotFoundError
Full Code Sample
Below is the full code sample we’ll be using in this article. It can be copied and pasted if you’d like to play with the code yourself and see how everything works.
# outer_import_2.7.py
import sys
import gw_utility.Book
def main():
try:
print(sys.version)
except ImportError as error:
# Output expected ImportErrors.
print(error.__class__.__name__ + ": " + error.message)
except Exception as exception:
# Output unexpected Exceptions.
print(exception, False)
print(exception.__class__.__name__ + ": " + exception.message)
if __name__ == "__main__":
main()
# inner_import_2.7.py
import sys
def main():
try:
print(sys.version)
import gw_utility.Book
except ImportError as error:
# Output expected ImportErrors.
print(error.__class__.__name__ + ": " + error.message)
except Exception as exception:
# Output unexpected Exceptions.
print(exception, False)
print(exception.__class__.__name__ + ": " + exception.message)
if __name__ == "__main__":
main()
# outer_import_3.6.py
import sys
import gw_utility.Book
from gw_utility.logging import Logging
def main():
try:
Logging.log(sys.version)
except ImportError as error:
# Output expected ImportErrors.
Logging.log_exception(error)
# Include the name and path attributes in output.
Logging.log(f'error.name: {error.name}')
Logging.log(f'error.path: {error.path}')
except Exception as exception:
# Output unexpected Exceptions.
Logging.log_exception(exception, False)
if __name__ == "__main__":
main()
# inner_import_3.6.py
import sys
from gw_utility.logging import Logging
def main():
try:
Logging.log(sys.version)
import gw_utility.Book
except ImportError as error:
# Output expected ImportErrors.
Logging.log_exception(error)
# Include the name and path attributes in output.
Logging.log(f'error.name: {error.name}')
Logging.log(f'error.path: {error.path}')
except Exception as exception:
# Output unexpected Exceptions.
Logging.log_exception(exception, False)
if __name__ == "__main__":
main()
# logging.py
import math
import sys
import traceback
class Logging:
separator_character_default = '-'
separator_length_default = 40
@classmethod
def __output(cls, *args, sep: str = ' ', end: str = 'n', file=None):
"""Prints the passed value(s) to the console.
:param args: Values to output.
:param sep: String inserted between values, default a space.
:param end: String appended after the last value, default a newline.
:param file: A file-like object (stream); defaults to the current sys.stdout.
:return: None
"""
print(*args, sep=sep, end=end, file=file)
@classmethod
def line_separator(cls, value: str = None, length: int = separator_length_default,
char: str = separator_character_default):
"""Print a line separator with inserted text centered in the middle.
:param value: Inserted text to be centered.
:param length: Total separator length.
:param char: Separator character.
"""
output = value
# If no value passed, output separator of length.
if value == None or len(value) == 0:
output = f'{char * length}'
elif len(value) < length:
# Update length based on insert length, less a space for margin.
length -= len(value) + 2
# Halve the length and floor left side.
left = math.floor(length / 2)
right = left
# If odd number, add dropped remainder to right side.
if length % 2 != 0:
right += 1
# Surround insert with separators.
output = f'{char * left} {value} {char * right}'
cls.__output(output)
@classmethod
def log(cls, *args, sep: str = ' ', end: str = 'n', file=None):
"""Prints the passed value(s) to the console.
:param args: Values to output.
:param sep: String inserted between values, default a space.
:param end: String appended after the last value, default a newline.
:param file: A file-like object (stream); defaults to the current sys.stdout.
"""
cls.__output(*args, sep=sep, end=end, file=file)
@classmethod
def log_exception(cls, exception: BaseException, expected: bool = True):
"""Prints the passed BaseException to the console, including traceback.
:param exception: The BaseException to output.
:param expected: Determines if BaseException was expected.
"""
output = "[{}] {}: {}".format('EXPECTED' if expected else 'UNEXPECTED', type(exception).__name__, exception)
cls.__output(output)
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_tb(exc_traceback)
When Should You Use It?
The seemingly simple import
statement found in Python is actually rather complex when looking under the hood. At the most basic level an import
statement is used to perform two tasks. First, it attempts to find the module specified by name, then loads and initializes it, if necessary. It also automatically defines a name in the local namespace within the scope of the associated import
statement. This local name can then be used to reference the the accessed module throughout the following scoped code.
While the import
statement is the most common technique used to gain access to code from other modules, Python also provides other methods and functions that makeup the built-in import system. Developers can opt to use specific functions to have more fine-grained control over the import process.
For our code samples we’ll stick to the common import
statement that most of us are accustomed to. As mentioned in the introduction, behavior for failed imports
differs depending on the Python version. To illustrate we start with the outer_import_2.7.py
file:
# outer_import_2.7.py
import sys
import gw_utility.Book
def main():
try:
print(sys.version)
except ImportError as error:
# Output expected ImportErrors.
print(error.__class__.__name__ + ": " + error.message)
except Exception as exception:
# Output unexpected Exceptions.
print(exception, False)
print(exception.__class__.__name__ + ": " + exception.message)
if __name__ == "__main__":
main()
The outer
prefix for the file name indicates that we’re testing an «outer» or globally scoped import
statement of gw_utility.Book
. Executing this code produces the following output:
Traceback (most recent call last):
File "C:UsersGabeAppDataLocalJetBrainsToolboxappsPyCharm-Pch-0172.3968.37helperspydevpydevd.py", line 1599, in <module>
globals = debugger.run(setup['file'], None, None, is_module)
File "C:UsersGabeAppDataLocalJetBrainsToolboxappsPyCharm-Pch-0172.3968.37helperspydevpydevd.py", line 1026, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "D:/work/Airbrake.io/Exceptions/Python/BaseException/Exception/ImportError/outer_import_2.7.py", line 3, in <module>
import gw_utility.Book
ImportError: No module named Book
The overall issue here is that the gw_utility.Book
module doesn’t exist. In fact, the proper module is lowercase: gw_utility.book
. Since the import
statement is at the top of the file, it exists outside our try-except
block, so the ImportError
we get in the log is not caught — execution was terminated entirely when the error was raised.
Alternatively, let’s see what happens if we move the import
statement inside a try-except
block, as seen in inner_import_2.7.py
:
# inner_import_2.7.py
import sys
def main():
try:
print(sys.version)
import gw_utility.Book
except ImportError as error:
# Output expected ImportErrors.
print(error.__class__.__name__ + ": " + error.message)
except Exception as exception:
# Output unexpected Exceptions.
print(exception, False)
print(exception.__class__.__name__ + ": " + exception.message)
if __name__ == "__main__":
main()
Running this code — also using Python 2.7 — produces the same ImportError
, but we’re able to catch it and perform further processing of the caught ImportError
, if necessary:
2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:25:58) [MSC v.1500 64 bit (AMD64)]
ImportError: No module named Book
The ModuleNotFoundError
was added in Python 3.6 as a subclass of ImportError
and an explicit indication of the same kind of errors we’re seeing above in the 2.7 code. For example, let’s look at the outer import
example in Python 3.6 with outer_import_3.6.py
:
# outer_import_3.6.py
import sys
import gw_utility.Book
from gw_utility.logging import Logging
def main():
try:
Logging.log(sys.version)
except ImportError as error:
# Output expected ImportErrors.
Logging.log_exception(error)
# Include the name and path attributes in output.
Logging.log(f'error.name: {error.name}')
Logging.log(f'error.path: {error.path}')
except Exception as exception:
# Output unexpected Exceptions.
Logging.log_exception(exception, False)
if __name__ == "__main__":
main()
Once again, here we’re performing the import
outside the try-except
block, so running this code halts execution and produces the following output:
Traceback (most recent call last):
File "C:UsersGabeAppDataLocalJetBrainsToolboxappsPyCharm-Pch-0172.3968.37helperspydevpydevd.py", line 1599, in <module>
globals = debugger.run(setup['file'], None, None, is_module)
File "C:UsersGabeAppDataLocalJetBrainsToolboxappsPyCharm-Pch-0172.3968.37helperspydevpydevd.py", line 1026, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:UsersGabeAppDataLocalJetBrainsToolboxappsPyCharm-Pch-0172.3968.37helperspydev_pydev_imps_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"n", file, 'exec'), glob, loc)
File "D:/work/Airbrake.io/Exceptions/Python/BaseException/Exception/ImportError/outer_import_3.6.py", line 3, in <module>
import gw_utility.Book
ModuleNotFoundError: No module named 'gw_utility.Book'
The cause of this error is the exact same as the 2.7 version, but with 3.6+ the more specific ModuleNotFoundError
is now raised. Additionally, we can actually catch such errors if the import
is executed within a try-except
context:
# inner_import_3.6.py
import sys
from gw_utility.logging import Logging
def main():
try:
Logging.log(sys.version)
import gw_utility.Book
except ImportError as error:
# Output expected ImportErrors.
Logging.log_exception(error)
# Include the name and path attributes in output.
Logging.log(f'error.name: {error.name}')
Logging.log(f'error.path: {error.path}')
except Exception as exception:
# Output unexpected Exceptions.
Logging.log_exception(exception, False)
if __name__ == "__main__":
main()
This code allows us to output the Python version and process the error:
3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
[EXPECTED] ModuleNotFoundError: No module named 'gw_utility.Book'
error.name: gw_utility.Book
error.path: None
We’re also outputting the name
and path
attributes of the ImportError
object, which were added in Python 3.3 to indicate the name of the module that was attempted to be imported, along with the path to the file that triggered the exception, if applicable. In this case our code is rather simple so, unfortunately, neither attribute is particularly useful.
Airbrake’s robust error monitoring software provides real-time error monitoring and automatic exception reporting for all your development projects. Airbrake’s state of the art web dashboard ensures you receive round-the-clock status updates on your application’s health and error rates. No matter what you’re working on, Airbrake easily integrates with all the most popular languages and frameworks. Plus, Airbrake makes it easy to customize exception parameters, while giving you complete control of the active error filter system, so you only gather the errors that matter most.
Check out Airbrake’s error monitoring software today and see for yourself why so many of the world’s best engineering teams use Airbrake to revolutionize their exception handling practices! Try Airbrake free with a 14-day free trial.
- Use the Correct Module Name to Solve
ModuleNotFoundError
in Python - Use the Correct Syntax to Solve
ModuleNotFoundError
in Python
Modules are important for developing Python programs. With modules, we can separate different parts of a codebase for easier management.
When working with modules, understanding how they work and how we can import them into our code is important. Without this understanding or mistakes, we may experience different errors.
One example of such an error is ModuleNotFoundError
. In this article, we will discuss the way to resolve ModuleNotFoundError
within Python.
Use the Correct Module Name to Solve ModuleNotFoundError
in Python
Let’s create a simple Python codebase with two files, index.py
and file.py
, where we import file.py
into the index.py
file. Both files are within the same directory.
The file.py
file contains the code below.
class Student():
def __init__(self, firstName, lastName):
self.firstName = firstName
self.lastName = lastName
The index.py
file contains the code below.
import fiIe
studentOne = fiIe.Student("Isaac", "Asimov")
print(studentOne.lastName)
Now, let’s run index.py
. The output of our code execution is below.
Traceback (most recent call last):
File "c:UsersakinlDocumentsPythonindex.py", line 1, in <module>
import fiIe
ModuleNotFoundError: No module named 'fiIe'
We have a ModuleNotFoundError
. If you look closely, you will notice that the import statement has a typographical error where file
is written as fiIe
with the l
replaced with a capital I
.
Therefore, if we use the wrong name, a ModuleNotFoundError
can be thrown at us. Be careful when writing your module names.
Now, let’s correct it and get our code running.
import file
studentOne = file.Student("Isaac", "Asimov")
print(studentOne.lastName)
The output of the code:
Also, we could rewrite the import
statement using the from
keyword and import
just the Student
class. This is useful for cases where we don’t want to import all the functions, classes, and methods present within the module.
from file import Student
studentOne = Student("Isaac", "Asimov")
print(studentOne.lastName)
We will get the same output as the last time.
Use the Correct Syntax to Solve ModuleNotFoundError
in Python
We can get a ModuleNotFoundError
when we use the wrong syntax when importing another module, especially when working with modules in a separate directory.
Let’s create a more complex codebase using the same code as the last section but with some extensions. To create this codebase, we need the project structure below.
Project/
data/
file.py
welcome.py
index.py
With this structure, we have a data
package that houses the file
and welcome
modules.
In the file.py
file, we have the code below.
class Student():
def __init__(self, firstName, lastName):
self.firstName = firstName
self.lastName = lastName
In the welcome.py
, we have the code below.
def printWelcome(arg):
return "Welcome to " + arg
The index.py
contains code that tries to import file
and welcome
and uses the class Student
and function printWelcome
.
import data.welcome.printWelcome
import data.file.Student
welcome = printWelcome("Lagos")
studentOne = Student("Isaac", "Asimov")
print(welcome)
print(studentOne.firstName)
The output of running index.py
:
Traceback (most recent call last):
File "c:UsersakinlDocumentsPythonindex.py", line 1, in <module>
import data.welcome.printWelcome
ModuleNotFoundError: No module named 'data.welcome.printWelcome'; 'data.welcome' is not a package
The code tried to import the function printWelcome
and class Student
using the dot operator directly instead of using the from
keyword or the __init__.py
for easy binding for submodules. By doing this, we have a ModuleNotFoundError
thrown at us.
Let’s use the correct import
statement syntax to prevent ModuleNotFoundError
and import the function and class directly.
from data.file import Student
from data.welcome import printWelcome
welcome = printWelcome("Lagos")
studentOne = Student("Isaac", "Asimov")
print(welcome)
print(studentOne.firstName)
The output of the code:
We can bind the modules (file
and welcome
) within the data
package to its parent namespace. To do this, we need the __init__.py
file.
In the __init__.py
file, we import all the modules and their functions, classes, or objects within the package to allow easy management.
from .file import Student
from .welcome import printWelcome
Now, we can write our index.py
more succinctly and with a good binding to the parent namespace, data
.
from data import Student, printWelcome
welcome = printWelcome("Lagos")
studentOne = Student("Isaac", "Asimov")
print(welcome)
print(studentOne.firstName)
The output will be the same as the last code execution.
To prevent the ModuleNotFoundError
error message, ensure you don’t have a wrong import
statement or typographical errors.