I don't think any language causes as much headache as python in so simple a thing as importing other source files. So here is the question: Do my module imports need to depend on how the code is supposed to run?
I have the following directory structure:
./__init__.py
./config.py
./kmer
./kmer/__init__.py
./kmer/__main__.py
./kmer/__pycache__
./kmer/__pycache__/__init__.cpython-36.pyc
./kmer/__pycache__/__main__.cpython-36.pyc
./kmer/__pycache__/bed.cpython-36.pyc
./kmer/__pycache__/config.cpython-36.pyc
./kmer/__pycache__/reference.cpython-36.pyc
./kmer/__pycache__/sets.cpython-36.pyc
./kmer/bed.py
./kmer/config.py
./kmer/reference.py
./kmer/sets.py
I wish to import a module inside the khmer
from another module inside the kmer
package. Simple?
So I add this at the of the bed.py
:
import reference
import config
import sets
Now thing will work just fine if I run python bed.py
from the kmer
directory. Also things are fine if I come back one directory and call python kmer/bed.py
. Seems like python searches for imported modules relative to the given file.
Again running it as python -m bed
from the kmer
directory works fine but coming back one directory and running python -m kmer.bed
results in module errors. Here it seem like python looks for modules inside the interpreter's current directory which could be anywhere on the file system so imports relative to it shouldn't work.
This basically means that the imports should depend on how the code is going to be run which makes no sense. I'd appreciate some explanation on how this is supposed to work.
I've looked at quite a lot of resources including the answer to this question which although very detailed (one of the best descriptions I've found actually) doesn't solve my problem and also doesn't provide proper examples.
Update: I believe this question is more focused on a different aspect of relative import, more precisely how different methods of running the code affect the imports, than the one it is marked as a duplicate of. Thats why I mentioned the other question in first place. Hence I don't think this should be a duplicate.