Anton
Anton

Reputation: 4815

Can't Import Using Absolute Path

I have a very simple test Python 3 project with the following file structure:

test/a.py
test/b.py
test/__init__.py

Everywhere I read, people say that in a.py I should import b.py using an absolute path:

from test.b import *

However, when I try I get the following error:

Traceback (most recent call last):
  File "a.py", line 1, in <module>
    from test.b import *
ModuleNotFoundError: No module named 'test.b'

I understand that I can import b.py using from b import *, however this is not what people recommend. They all recommend from test.b import *. But I can't get even this simple example to work.

Upvotes: 3

Views: 2374

Answers (2)

overflo
overflo

Reputation: 355

As Martijn said in the comment, it depends on how you call a.py. If you call it directly from within the directory by typing python a.py you will get the error above.

However, if you call it like that: python -m test.a while being one directory above the test directory, your import will work just fine.

Upvotes: 8

Hou Lu
Hou Lu

Reputation: 3222

The common directory structure is like this:

test/a.py
test/b.py
test/__init__.py
run.py

The main code should be put into run.py. When you want to import a.py in run.py, just write from test.a import * or something like that. And if you need to import b.py in a.py, do as you have been told from test.b import *. Then, run run.py would get the correct result.

Upvotes: 3

Related Questions