Search code examples
pythonimportnestedsiblings

Python import module from a subfolder that imports a sibling module


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


Solution

  • 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