19

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!"

I instead get:

ImportError: No module named a

What in the world is going on here? I feel like I'm missing something basic. While this example is trivial, I need absolute imports to work for the real project, so just replacing the import with a relative one is not an option. I'm using python 2.7.13

None of the solutions listed here help

Thanks in advance for any insight!

lbear
  • 305
  • 1
  • 3
  • 6
  • 1
    Is `foo.py` inside the `a` directory? You're showing it as outside in your diagram. – user2357112 Aug 01 '17 at 21:50
  • my bad, thanks for the catch – lbear Aug 01 '17 at 21:51
  • 1
    It sounds like you're making the common mistake of running a submodule of a package directly instead of as a submodule. There's a dupe somewhere around here - tons of dupes, really, but I think there's at least one good one. – user2357112 Aug 01 '17 at 21:52
  • Can you elaborate a little? I'm still a little confused as to what the problem is. – lbear Aug 01 '17 at 22:00
  • I'm not sure, but maybe what @user2357112 says is that you should be writing down `import a.b` since `b` is a submodule of `a` – Arthur Spoon Aug 01 '17 at 22:01
  • No cigar, unfortunately: `ImportError: No module named a.b` – lbear Aug 01 '17 at 22:05
  • Is `a` in your `sys.path`? I have a strong feeling that the answer is "no", in which case it really is no surprise that `import a` fails. – Aran-Fey Aug 01 '17 at 22:06

1 Answers1

40

Since it's not shown, I have to assume you're running python a/foo.py, this puts the directory of the script ('a') on the beginning of sys.path when in reality you want the current directory on the beginning of sys.path.

You should instead run python -m a.foo which will correctly initialize the sys.path roots for your project structure.

Here's a more in-depth writeup that I wrote on other ways this same problem can go pearshaped.

Additionally I recorded a video on the topic: don't run python my/script.py!

anthony sottile
  • 61,815
  • 15
  • 148
  • 207