0

I have already read Python: importing a sub‑package or sub‑module but this:

file                                content
============================================================================
main.py                             from mymodule.a import A; A()
mymodule/submodule/__init__.py      (empty)
mymodule/submodule/b.py             class B: pass
mymodule/__init__.py                (empty)
mymodule/a.py                       (see below)

mymodule/a.py:

import submodule
class A:
    def __init__(self):
        self.b = submodule.B()

fails with:

File "a.py", line 1, in
import submodule
ModuleNotFoundError: No module named 'submodule'

when lauching the script main.py.

Question: how should I import submodule in mymodule/a.py?

Basj
  • 41,386
  • 99
  • 383
  • 673
  • Have you tried placing 'submodule.py' inside the 'a.py' directory? it would be helpful if you could post the file hierarchy of the project – Esvin Joshua Jun 21 '22 at 14:50
  • @EsvinJoshua Not possible, submodule is not a .py file, it's a directory. See my question, the file hierarchy/tree structure is in the first column. – Basj Jun 21 '22 at 14:52
  • I assume that you have to write "from b import B" in your submodule/init.py and then from mymodule/a.py you should be able to make "from submodule import B" – ottonormal Jun 21 '22 at 14:58
  • well in that case you would have to ( as @ottonormal) suggested, get the directory then get the file; from submodule import b.py – Esvin Joshua Jun 21 '22 at 14:59
  • What is the canonical way to do this? This is a common scenario when writing modules with submodules. – Basj Jun 21 '22 at 14:59
  • 1
    check out this SO post: [How to import .py file from another directory?](https://stackoverflow.com/questions/22955684/how-to-import-py-file-from-another-directory) I think this is what you are looking for? – Esvin Joshua Jun 21 '22 at 15:04
  • for my understanding is this the right way to do this. The answer from Gabriel d'Agosto could work too, but you will not being able to import specific classes or functions from that package. Only the whole one – ottonormal Jun 21 '22 at 15:07

1 Answers1

2

TLDR:

mymodule/a.py:

from . import submodule
# or
import mymodule.submodule as submodule

Once you run your main.py, python adds to your sys.path the path to main.py folder. Python can now search subfolders to find modules trying to be imported. Once you import a.py, python DOES NOT add anything else to sys.path, therefore, to be able import subfolders, you need to do either relative importing (from . import submodule), which you can do because you aren't running a.py as your main file, OR do a full import, doing import mymodule.submodule, since python can search starting on main.py folder.

Basj
  • 41,386
  • 99
  • 383
  • 673
Gabriel d'Agosto
  • 416
  • 3
  • 12