2

I have a Python 2.7 project that looks like this:

myproject\

- __init__.py
- __main__.py
- foo.py

I'd like to use absolute imports, as required by PEP 8, but when I try to do this in __main__.py:

from myproject.foo import bar

With python -m myproject

I get:

ImportError: No module named myproject.foo

What am I doing wrong?

Community
  • 1
  • 1
Sean W.
  • 4,944
  • 8
  • 40
  • 66

2 Answers2

2

After a bit more Googling it turns out, all I needed to do was add:

from __future__ import absolute_import

This adds some future-proofing for Python 3.Note that PyDev cannot find the modules this way. I'll open a separate question for that.

Community
  • 1
  • 1
Sean W.
  • 4,944
  • 8
  • 40
  • 66
1

For that to work, myproject has to be on your Python path. You can do that externally by setting the PYTHONPATH variable, or inside the program by adding it to sys.path.

(Note that there's no convention to use double-underscore names on anything other than __init__.py. Your __main__.py seems a very odd name.)

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895