0

So, I encountered a ModuleNotFoundError when trying to import a module in a subpackage that imports another subpackage under its directory (so it's a subsubpackage to the main directory). I have put empty __init__.py files under both the subdirectory and subsubdirectory. The code was run in Python 3.9.7.

Here's what the structure looks like:

|- main.py
|- subpackage/
   |- __init__.py
   |- submod.py
   |- subsubpackage/
      |- __init__.py
      |_ subsubmod.py

The code

In main.py, I have:

from subpackage import submod

def main():
    x = submod.test_func(3)
    print(x)

if __name__ == 'main':
    main()

and in submod.py, I want to import subsubmod.py under subsubpackage/, so I have:

from subsubpackage import subsubmod

def test_func(a):
    return subsubmod.addone(a)

and finally, in subsubmod.py:

def addone(x):
    return x+1

The error message:

Now if I run main.py, I got

Traceback (most recent call last):

File "/Users/anonymous/test/main.py", line 1, in 
<module>
from subpackage import submod

File "/Users/anonymous/test/subpackage/submod.py", 
line 1, in <module>
from subsubpackage import subsubmod

ModuleNotFoundError: No module named 'subsubpackage'

My question and confusion

I'm not sure what I have done wrong. I realized that submod.py can be run separately, so it seems that the issue occurs when the import goes down more than one subdirectory? I wonder if there's a way around this issue, or should I just use a different structure to organize my scripts.

Cory
  • 1
  • 1

2 Answers2

0

Putting a dot before the package name worked for me.

from .subsubpackage import subsubmod

Looks like when you are in a package if you don't use relative import it will look for your packages somewhere else.

You can find more information here:
Python documents about import system
StackOverflow question about relative imports

0

This question keeps showing up on Stack Overflow and I can understand why. So today I took the time to create a nested project with 1 top module and 2 nested sub modules both with classes in them. And another class was also created in the top module folder. This is also considered a module by python. But it's in the same folder as the top module.

The skeleton nested module project is now live on Github at:

HdlHelpers Nested Modules Skeleton Project