Что означает ошибка 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
- 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.