In order to import modules with package path with dot separators, all sub-directories must come with the __init__.py files.

Example directory structure:

project1/
..modules/
....submodule1/
......__init__.py
......file2.py
....submodule2/
......__init__.py
......file3.py
....__init__.py
....file1.py
..main.py

Python standard import:

#main.py:

from modules.file1            import someclassname
from modules.submodule1.file2 import someclassname
from modules.submodule2.file3 import someclassname

Python relative path import from path of current file:

#use the same directory structure above
#example content for file3.py:

import os
import sys

#paths for relative modules (from current file)
__realpath__ = os.path.realpath(__file__)
__dirname__  = os.path.dirname(__realpath__)
sys.path.append(__dirname__+"/..") #parent dir
sys.path.append(__dirname__+"/../submodule1") #sibling dir

from file1 import someclassname
from file2 import someclassname
Advertisements