'What's the right way to ensure the module is available to its main.py?
I usually structure my projects like this in a git repo(with __init__.pys in every subfolder of the module):
/
|
+-src/
|
+-my_module/
|
+-__init__.py
+-main.py
+-importA/
+-importB/
...
and run the main.py using python src/my_module/main.py or I use a __main__.py and just call the folder. However in the main I need to usually import from one or more subfolders and they sometimes need to import amongst each other(e.g. a shared util folder). I do this with absolute module imports so something like:
from my_module.importA import something
from my_module.importB import something_else as se
For this to work I need to make sure the package is on the PYTHONPATH. This can be done by various methods, but not all are always respected by all IDEs or when ran from the commandline. So at the top of my main.py I usually have the following:
import os
import sys
# add module to pythonpath
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
# other imports
Which my linter complains about because I don't have all imports on the top of the file; so while this works, it doesn't seem to be the ideal or intended way to do this. I tried adding these three lines to the __init__.py but that only works if I import the module itself, which I can only do if it's on the path already.
So, what's the intended, or best way to ensure that your module is available for absolute imports from anywhere (assuming the main.py was run or imported).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
