I have a file structure like this:
- __init__.py
- module.py
+ subpackage
|--- __init__.py
|--- submodule1.py
|--- submodule2.py
|--- etc
- submodule1.py imports from submodule2.py
- module imports from submodule1.py
To do this, I'm using relative imports. For example, in submodule1.py:
from .submodule2 import MyClass
The problem I'm running into is that now, using relative imports, I can't run submodule1.py as main. If I try, I get this error:
from .module2 import MyClass
ModuleNotFoundError: No module named '__main__.module2'; '__main__' is not a package
I like to include an if __name__ == "__main__":
at the end of my modules for testing during development (and in some contexts a module might even be useful as a standalone script).
Is there a way to "have my cake and eat it too" on this one? Or is my best bet to migrate the code from if __name__ == "__main__":
to a separate script?