Currently trying to work in Python3 and use absolute imports to import one module into another but I get the error ModuleNotFoundError: No module named '__main__.moduleB'; '__main__' is not a package
. Consider this project structure:
proj
__init__.py3 (empty)
moduleA.py3
moduleB.py3
moduleA.py3
from .moduleB import ModuleB
ModuleB.hello()
moduleB.py3
class ModuleB:
def hello():
print("hello world")
Then running python3 moduleA.py3
gives the error. What needs to be changed here?
Thank you!
.moduleB
is a relative import. Relative only works when the parent module is imported or loaded first. That means you need to have proj
imported somewhere in your current runtime environment. When you are are using command python3 moduleA.py3
, it is getting no chance to import parent module. You can:
from proj.moduleB import moduleB
OR
- You can create another script, let's say
run.py
, to invoke from proj import moduleA
Good luck with your journey to the awesome land of Python.
In addition to md-sabuj-sarker's answer, there is a really good example in the Python modules documentation.
This is what the docs say about intra-package-references:
Note that relative imports are based on the name of the current module. Since the name of the main module is always "__main__"
, modules intended for use as the main module of a Python application must always use absolute imports.
If you run python3 moduleA.py3
, moduleA
is used as the main module, so using the absolute import looks like the right thing to do.
However, beware that this absolute import (from package.module import something
) fails if, for some reason, the package contains a module file with the same name as the package (at least, on my Python 3.7). So, for example, it would fail if you have (using the OP's example):
proj/
__init__.py (empty)
proj.py (same name as package)
moduleA.py
moduleB.py
in which case you would get:
ModuleNotFoundError: No module named 'proj.moduleB'; 'proj' is not a package
Alternatively, you could remove the .
in from .moduleB import
, as suggested here and here, which seems to work, although my PyCharm (2018.2.4) marks this as an "Unresolved reference" and fails to autocomplete.