Why this recursive import fails?

INADA Naoki songofacandy at gmail.com
Wed Mar 7 03:47:25 CET 2012


I have 4 py files like below. Two __init__.py is empty file.

$ find foo -name "*.py"
foo/lib/lib.py
foo/lib/__init__.py
foo/__init__.py
foo/foo.py

$ cat foo/lib/lib.py
from __future__ import absolute_import
print('lib.py', __name__)
from .. import foo
#import foo.foo

$ cat foo/foo.py
from __future__ import absolute_import
print('foo.py', __name__)
from .lib import lib
#import foo.lib.lib

Then, importing foo.foo or foo.lib.lib fails unexpectedly.

# `from .. import foo` success but `from .lib import lib` fails.
$ python -c "import foo.lib.lib"
('lib.py', 'foo.lib.lib')
('foo.py', 'foo.foo')
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "foo/lib/lib.py", line 3, in <module>
    from .. import foo
  File "foo/foo.py", line 3, in <module>
    from .lib import lib
ImportError: cannot import name lib

# `from .lib import lib` success but `from .. import foo` fails.
$ python -c "import foo.foo"
('foo.py', 'foo.foo')
('lib.py', 'foo.lib.lib')
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "foo/foo.py", line 3, in <module>
    from .lib import lib
  File "foo/lib/lib.py", line 3, in <module>
    from .. import foo
ImportError: cannot import name foo


I can run both with absolute import.
What's wrong about my relative import?



More information about the Python-list mailing list