简体   繁体   中英

Python: ModuleNotFoundError encountered when importing modules from nested folders

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.

Uh.. What? there is no module named subsubpackage, only subsubpackage/. Please check your code again.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM