Reputation: 45
Why am I getting import error for a module I have in the project. All the packages are under the project, they all have __init __.py and other scripts do not give the same error. Python version is 3.6. Code was written in Unix environment.
Here is the import error I get. I am trying to run a test here.
Ran 1 test in 0.001s
FAILED (errors=1)
Error
Traceback (most recent call last):
File "/usr/lib/python3.6/unittest/case.py", line 59, in testPartExecutor
yield
File "/usr/lib/python3.6/unittest/case.py", line 605, in run
testMethod()
File "/usr/lib/python3.6/unittest/loader.py", line 34, in testFailure
raise self._exception
ImportError: Failed to import test module: test_SMSHandler
Traceback (most recent call last):
File "/usr/lib/python3.6/unittest/loader.py", line 153, in loadTestsFromName
module = __import__(module_name)
File "/home/sevvalboylu/server/app/api/test_SMSHandler.py", line 11, in <module>
from middleware.services import Sender
ModuleNotFoundError: No module named 'middleware'
Upvotes: 2
Views: 5490
Reputation: 1618
I've experienced a similar problem with import error when running unit tests (with correct importable structure), but the cause and the solution are different to described in the answer above. Still this is relevant and may help somebody.
In my case I have structure like that (__init__.py
present but omitted below for brevity):
mypkg
\-- foo.py
another
tests
\-- some
\-- <tests here>
mypkg <--- same name as top level module mypkg
\-- test_a.py
When running from top level directory imports in test_a.py
of modules from mypkg
were failing:
# test_a.py
from mypkg import foo # causes ModuleNotFoundError: No module named 'mypkg.foo'
Renaming mypkg
folder under tests
folder into something else solved the problem.
Upvotes: 1
Reputation: 8039
Looks like you are missing a project's root path in PYTHONPATH
From the docs (Modules - The Module Source Path)
When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:
- The directory containing the input script (or the current directory when no file is specified).
- PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
- The installation-dependent default.
If this solution doesn't work for you, please post the project's tree to make it easier find the problem.
Upvotes: 1