python - Relative imports - ModuleNotFoundError: No module named x

ID : 10451

viewed : 43

Tags : pythonpython-3.xpackagepython-importrelative-importpython

Top 5 Answer for python - Relative imports - ModuleNotFoundError: No module named x

vote vote


TL;DR: You can't do relative imports from the file you execute since __main__ module is not a part of a package.

Absolute imports - import something available on sys.path

Relative imports - import something relative to the current module, must be a part of a package

If you're running both variants in exactly the same way, one of them should work. Here is an example that should help you understand what's going on. Let's add another file with the overall directory structure like this:

. ./ ./ryan/ ./ryan/ ./ryan/ 

And let's update to see what's going on:

# debug = True 
# print(__name__)  try:     # Trying to find module in the parent package     from . import config     print(config.debug)     del config except ImportError:     print('Relative import failed')  try:     # Trying to find module on sys.path     import config     print(config.debug) except ModuleNotFoundError:     print('Absolute import failed') 
# import ryan.test 

Let's run first:

$ python ryan/ __main__ Relative import failed True 

Here "test" is the __main__ module and doesn't know anything about belonging to a package. However import config should work, since the ryan folder will be added to sys.path.

Let's run instead:

$ python ryan.test True Absolute import failed 

And here test is inside of the "ryan" package and can perform relative imports. import config fails since implicit relative imports are not allowed in Python 3.

Hope this helped.

P.S.: If you're sticking with Python 3 there is no more need for files.

vote vote


I figured it out. Very frustrating, especially coming from python2.

You have to add a . to the module, regardless of whether or not it is relative or absolute.

I created the directory setup as follows.

/ --/lib   --/   --/   --/

def does_something():     return "I gave you this string."

from modx import does_something  def loaded():     string = does_something()     print(string)

from lib import mody  mody.loaded() 

when I execute main, this is what happens

$ python Traceback (most recent call last):   File "", line 2, in <module>     from lib import mody   File "/mnt/c/Users/Austin/Dropbox/Source/Python/virtualenviron/mock/package/lib/", line 1, in <module>     from modx import does_something ImportError: No module named 'modx' 

I ran 2to3, and the core output was this

RefactoringTool: Refactored lib/ --- lib/ (original) +++ lib/ (refactored) @@ -1,4 +1,4 @@ -from modx import does_something +from .modx import does_something   def loaded():      string = does_something() RefactoringTool: Files that need to be modified: RefactoringTool: lib/ RefactoringTool: lib/ 

I had to modify's import statement to fix it

try:     from modx import does_something except ImportError:     from .modx import does_something   def loaded():     string = does_something()     print(string) 

Then I ran again and got the expected output

$ python I gave you this string. 

Lastly, just to clean it up and make it portable between 2 and 3.

from __future__ import absolute_import from .modx import does_something 
vote vote


You have to append your project's path to PYTHONPATH and make sure to use absolute imports.

For UNIX (Linux, OSX, ...)

export PYTHONPATH="${PYTHONPATH}:/path/to/your/project/" 

For Windows

set PYTHONPATH=%PYTHONPATH%;C:\path\to\your\project\ 

Absolute imports

Assuming that we have the following project structure,

└── myproject     ├── mypackage     │   ├──     └── anotherpackage         ├──         ├──         └── mysubpackage             └── 

just make sure to reference each import starting from the project's root directory. For instance,

# in module import anotherpackage.mysubpackage.d  # in module b import anotherpackage.c import mypackage.a 

For a more comprehensive explanation, refer to the article How to fix ModuleNotFoundError and ImportError

vote vote


Setting PYTHONPATH can also help with this problem.

Here is how it can be done on Windows


vote vote


You can simply add following file to your tests directory, and then python will run it before the tests file  import os import sys sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) 

Top 3 video Explaining python - Relative imports - ModuleNotFoundError: No module named x