Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't Import Using Absolute Path

Tags:

python

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.

like image 210
Anton Avatar asked Jun 18 '26 02:06

Anton


1 Answers

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.

like image 177
overflo Avatar answered Jun 20 '26 16:06

overflo