Search code examples
pythonmodulepackagedirectory-structure

How to load python module from a neighbouring package?


I've made two python packages as follows:

theMainFolder/
├── package_a/
│   ├── __init__.py
│   └── some_a_file.py
├──package_b/
│   ├── __init__.py
│   └── some_b_file.py

I now want to import some_a_file into some_b_file. I tried doing this using:

from package_a import some_a_file

but this doesn't work. Does anybody know how I can do this? All tips are welcome.


Solution

  • Relatively add path to the location of theMainFolder and then do an import

    import sys                                               
    from os.path import dirname, abspath                     
    sys.path.insert(0, dirname(dirname(abspath(__file__))))  
    from package_a import some_a_file