Search code examples
pythonpython-importdirectory-structure

Python - Import from deeper subfolder


Somehow I couldn't find the exact answer to this elsewhere on SO.

Given:

root\
    __init__.py
    main.py
    folder0\
        __init__.py
        folder1\
             __init__.py
             class1.py
        folder2\
             __init__.py
             class2.py

Is there a way to import the top level directory as a whole? e.g.

# main.py
import folder0
obj1 = folder0.folder1.class1.Class1()
obj2 = folder0.folder2.class2.Class2()

Or do I have to import the modules directly? e.g.

# main.py
from folder0.folder1 import class1
from folder0.folder2 import class2
obj1 = class1.Class1()
obj2 = class2.Class2()

Solution

  • Sure. You just need to add the relevant imports into the __init__.py all the way down. e.g.:

    # folder2/__init__.py
    from . import class2
    

    and

    # folder0/__init__.py
    from . import folder1
    from . import folder2
    

    and so-on.