Questions about this issue have been asked many times but I'm afraid I still cannot fathom why a module which imports from a subdirectory, works when I call the module from its own directory, but when I import it from another directory I get ModuleNotFoundError: No module named _nested_package
. Here is the exact situation:
tbrowne@nd2110:~/scratch$ tree
.
└── topmodule
├── __init__.py
├── main.py
├── nest
│ ├── __init__.py
│ └── nestmodule.py
└── topmodule.py
now here is main.py:
from topmodule import test_add_two
if __name__ == "__main__":
print(test_add_two(11, 12))
here is topmodule.py:
from nest.nestmodule import add_two
def test_add_two(x, y):
return add_two(x, y)
if __name__ == "__main__":
print(test_add_two(1, 2))
And here is nestmodule.py:
def add_two(x, y):
return x + y
Now if I run main.py, from its own directory, no problem:
tbrowne@nd2110:~/scratch/topmodule$ python3 main.py
23
however if I move to the directory above, say scratch, and create nesttest.py:
tbrowne@nd2110:~/scratch$ cat nesttest.py
from topmodule.topmodule import test_add_two
if __name__ == "__main__":
print(test_add_two(3, 4))
Then I run it:
tbrowne@nd2110:~/scratch$ python3 nesttest.py
Traceback (most recent call last):
File "/home/tbrowne/scratch/nesttest.py", line 1, in <module>
from topmodule.topmodule import test_add_two
File "/home/tbrowne/scratch/topmodule/topmodule.py", line 1, in <module>
from nest.nestmodule import add_two
ModuleNotFoundError: No module named 'nest'
Issue is, I'm going to want to package this with Poetry or some other package creator, and I want topmodule
from wherever it is imported, even if it is packaged up, to be able to import the nest.nestmodule
's functions.
I'm hoping that by being very explicit on the exact situation, someone can help me on how to do this. The wider context in the real project I'm working on (not this toy analogous example) is that I am using git submodules inside other git repos, and these will have to be packaged up along with the main repo.