I have package p that has modules a and b. a relies on b:
b.py contents:
import a
However I want to ensure that b imports my a module from the same p package directory and not just any a module from PYTHONPATH.
So I’m trying to change b.py like the following:
from . import a
This works as long as I import b when I’m outside of p package directory. Given the following files:
/tmp
/p
a.py
b.py
__init__.py
The following works:
$ cd /tmp
$ echo 'import p.b' | python
The following does NOT work:
$ cd /tmp/p
$ echo 'import b' | python
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "b.py", line 1, in <module>
from . import a
ValueError: Attempted relative import in non-package
Why?
P.S. I’m using Python 2.7.3
After rereading the Python import documentation, the correct answer to my original problem is:
To ensure that
bimportsafrom its own package its just enough to write the following in theb:Here is the quote from the docs:
Note: As J.F. Sebastian suggest in the comment below, use of implicit imports is not advised, and they are, in fact, gone in Python 3.