Relative import bug or not?
Alexey Borzenkov
snaury at gmail.com
Sat Oct 14 18:51:02 EDT 2006
After reading PEP-0328 I wanted to give relative imports a try:
# somepkg/__init__.py
<empty>
# somepkg/test1.py
from __future__ import absolute_import
from . import test2
if __name__ == "__main__":
print "Test"
# somepkg/test2.py
<empty>
But it complaints:
C:\1\somepkg>test1.py
Traceback (most recent call last):
File "C:\1\somepkg\test1.py", line 1, in <module>
from . import test2
ValueError: Attempted relative import in non-package
Does this mean that packages that implement self tests are not allowed
to use relative import? Or is it just a bug? I can understand that I
can use "import test2" when it's __main__, but when it's not now it
complains about no module test2 with absolute_import on.
PEP-0328 also has this phrase: "Relative imports use a module's
__name__ attribute to determine that module's position in the package
hierarchy. If the module's name does not contain any package
information (e.g. it is set to '__main__') then relative imports are
resolved as if the module were a top level module, regardless of where
the module is actually located on the file system.", but maybe my
english knowledge is not really good, because I can't understand what
should actually happen here ("relative imports are resolved as if the
module were a top level module")... :-/
So is it a bug, or am I doing something wrong?
More information about the Python-list
mailing list