Simple way to manage module imports within a python package folder hierarchy

Anand
1 min readSep 24, 2020

There have been different guidelines for managing cross references within python packages — relative paths, absolute paths, adding references within __init__.py and using them elsewhere, and these have changed over time. I came back to setting that up for a package after a long while, and tripped over myself with relative paths, etc.

A bit of reading and testing revealed that the following simple approach a) works, b) is clean and also c)is most readable among alternatives:

  1. Add an empty __init__.py file in every folder that contains modules that you want to reference. (If you want your test runner to pick up tests, then add __init__.py to your test folders as well).
  2. Add absolute references from the top of the package down to the module you want to reference, even if the module is a sibling in the same folder.
  3. That’s it!

This works. There is no more to it — the reason I am posting this is that there are several sites and SO responses over the years that were correct at the time, but are no longer valid. Note that you may use other conveniences for the consumer of your package, by adding imports into __init__.py, etc. But to get things to work within the package, across source and test files, this just works.

--

--