Python import module from a subfolder that imports a sibling module

49 Views Asked by At

Folder structure:

ABC
|--db
|   |-- __init__.py
|   |-- post.py
|   |-- common.py
|   |-- connection.py
|-- __init__.py
|-- main.py

From main.py I want to import post.py in the db folder. Inside post.py I import some functions from common.py.

main.py contents: from db import post

post.py contents: from common import table_insert,get_row

Running main.py gives this error:

Traceback (most recent call last):
  File "/home/user/ABC/main.py", line 1, in <module>
    from db import post
  File "/home/user/ABC/db/post.py", line 1, in <module>
    from common import table_insert,get_row
ModuleNotFoundError: No module named 'common'

Additional info:

  • /home/user/ABC is in the sys.path
  • __init__.py files are empty

I've tried searching for a general description in the python documentation for how to import other modules that in turn imports other modules. No luck . I've searched Stackoverflow for similar cases - No luck finding any useable answers

2

There are 2 best solutions below

0
Voelv On BEST ANSWER

I solved it!

Changed the import statement in post.py to be fully qualified.

From

from common import table_insert,get_row

To

from db.common import table_insert,get_row
1
Bibhav On

In post.py, you must use relative import:

from .common import table_insert, get_row

Use of relative import is to refer in the same dir as post.py i.e db dir.

If you want to run individually you could do:

if __name__ == "__main__":
    from common import table_insert,get_row
else:
    from .common import table_insert, get_row