Search code examples
pythonpython-3.xprojectpython-import

What is the best way to structure Python projects using a shared package?


I am currently developing a package simultaneously with a few projects that use the package, and I'm struggling to figure out how to structure my directory tree and imports.

Ideally, I want something like this:

main_directory
├── shared_package
│   ├── __init__.py
│   ├── package_file1.py
│   └── package_file2.py
├── project1
│   ├── main.py
│   ├── module1.py
│   └── other_package
│       ├── __init__.py
│       └── other_package_file.py
└── project2
    └── ...

I can't figure out how to make the imports work cleanly for importing shared_package from python files in project1. Is there a preferred way to do this?

Any help would be appreciated!


Solution

  • shared_package will eventually be standalone. Other people will import and install it the normal way, and it'll be stored with the rest of the python modules in site-packages or wherever.

    To replicate this, I recommend just updating your PYTHONPATH to point to main_directory (or wherever you put shared_package anyway) - that way,

    import shared_package
    

    will still work fine for the code if shared_package was installed normally, because it's on the pythonpath either way.

    Note that PYTHONPATH is an environment variable, so the means for doing this will vary based on your operating system. Regardless, a quick search for how to modify the variable permanently on your OS should be easy.