I am struggling a bit to set up a working structure in one of my projects. The problem is, that I have main package and a subpackage in a structure like this (I left out all unn
Unfortunately relative imports and direct running of submodules don't mix.
Add the parent directory of mypackage
to your PYTHONPATH
or always cd
into the parent directory when you want to run a submodule.
Then you have two possibilities:
Use absolute (from mypackage import utils
) instead of relative imports (from . import utils
) and run them directly as before. The drawback with that solution is that you'll always need to write the fully qualified path, making it more work to rename mypackage
later, among other things.
or
Run python3 -m mypackage.utils
etc. to run your submodules instead of running python3 mypackage/utils.py
.
This may take some time to adapt to, but it's the more correct way (a module in a package isn't the same as a standalone script) and you can continue to use relative imports.
There are more "magical" solutions involving __package__
and sys.path
but they all require extra code at the top of every file with relative imports you want to run directly. I wouldn't recommend these.