(I realise there are a lot of questions on StackOverflow relating to python relative imports; I suspect also that I'm doing this all wrong; but here goes anyway ..)
I have a python project (mysubmod) organised as follows:
/__init__.py
/lib
- /__init__py
- /foobar.py
/models
- /__init__.py
- /hello.py
Importantly:
I then have a second project (myproj) into which I've imported mysubmod as a git submodule; myproj is now organised as follows -
/mysubmod
/scripts
- /__init__.py
- /__test.py
Where:
However when I run /scripts/test.py from the command line, the interpreter now complains that mysubmod/models/hello.py can no longer find lib.foobar.
Reload.
Changed mysubmod/models/hello.py so it now imports ..lib.foobar
Now I can run /scripts/test.py without complaint, but I can no longer run any of the submod scripts as files from the command line; I can only run them as modulles using the python -m option.
Also I can no longer run the submod project files on a standalone basis, even with the -m option, as the interpreter complains about 'Attempted relative import beyond toplevel package'; I have to go up a directory level, ie can only really run mysubmod from the myproj root (where it has mysubmod as the root level directory).
This all seems pretty unsatisfactory. I want to be able to:
Does anyone have any views on how to do this ? Any views on best practices with respect to git submodule and python ?
Thanks.
OK the answer is (after many wrong turns)
This way, the package structure is maintained whether you are working with the submod as a submodule or on a standalone basis.
You could also add mysubmod
to sys.path
when you starting your myproj
. Then mysubmod/models/hello.py
will find lib.foobar
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With