Absolute import in python doesn't work, relative import works
I can't seem to get absolute imports to work in python. Here is my file structure:
a/
b/
__init__.py
__init__.py
foo.py
foo.py:
# Including or removing the __future__ import has no effect
from __future__ import absolute_import
from a import b # just `import b` works fine
print "success!"
Instead, I get:
ImportError: No module named a
What's going on in the world here? I feel like I am missing something basic. Although this example is trivial, I need an absolute import to work in a real project, so just replacing the import with a relative one is not an option. I am using python 2.7.13
None of the listed solutions are here help
Thanks in advance for your understanding!
source to share
Since it is not shown, I have to assume what you are using python a/foo.py
, this puts the script ( 'a'
) directory at the beginning sys.path
, when in fact you want the current directory to start sys.path
.
Instead, you have to run python -m a.foo
that initializes the roots correctly sys.path
for your project structure.
Here's a deeper post I wrote in other ways, this same problem can go sad.
source to share