Basj
Basj

Reputation: 46393

Import a submodule in a Python module

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?

Upvotes: 0

Views: 2477

Answers (1)

Gabriel d'Agosto
Gabriel d'Agosto

Reputation: 494

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.

Upvotes: 3

Related Questions