Importing Sibling Packages in Python

I've put together a snippet of code to demonstrate how to import sibling packages and modules in Python 3, with a working example out on GitHub as python-sibling-import-example.

To run this, add this snippet to the start of any Python file in your project not at the root:

if __name__ == '__main__':
    import os
    import sys
    sys.path.append(os.getcwd())

To learn more about how and why this works, please review the associated README.

This solution was developed using Visual Studio Code on Windows, but I also tested this using Windows Subsystem for Linux(WSL) and the Visual Studio Code Remote Development after cloning the repository in WSL using the new Windows Terminal. Both ways worked fine, so long as I was running from the root of the directory.

I want to point out that this has been my way of solving the problem of not being able to load sibling packages in development. It's not necessarily the "Pythonic" or right way to make this work, but I was able to make it work consistently.

While Python does have documentation on imports, it only seemed to apply to when you test from the root with everything, not just one module. This is a recurring problem in the Python community.

If anyone runs this in a production environment, I'd love to hear feedback if this continues to work. All my Python work today is just scripts run from either my development environment, scheduled through SQL Server, or just a task scheduler on the server.

Author image
Hi, I'm Aaron Grossman, a Business Intelligence developer documenting what I've learned as I continue to grow my career. I can be reached at me@aaronjgrossman.com.