Multi-module Python project using an __init__.py file
06 May 2021
Updated: 03 September 2023
When creating a multi-module project for Python, especially when coming from another language ecosystem, you may encounter issues importing code from other files, let’s take a look at this
The Modules
In our project, we’ve got the following files:
Let’s say each of our modules export a function, here’s the code for them:
package1/module1.py
package2/subpackage1/module1.py
The Main
Now that we’ve got our files with their functions separated, we try using them from the main.py
file:
main.py
The Error
Now, we try to run this using python
:
And we get the following error:
The Solution
Now, this can be pretty annoying, but the solution is very simple. Python identifies a module
as a single file, and the assumption that leads to the issue above is that we assume a package
has the same convention of just being a directory
However, a packgage
requires an __init__.py
file to be defined so that they are recognized correctly
So, we need to add two files:
package1/__init__.py
package2/subpackage1/__init__.py
Additionally, these files are completely empty, and only serve as information. Note that we don’t need to include a file in package2
directly as this directory does not contain any modules within it so is not really a package in itself and is simply a wrapper subpackage1