I have two modules forming a circular import under a package
/test
__init__.py
a.py
b.py
a.py
import test.b
def a():
print("a")
b.py
import test.a
def b():
print("b")
But when I do "import test.a" from python interactive interpreter it throws AttributeError: module 'test' has no attribute 'a'
>>> import test.a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "test/a.py", line 2, in <module>
import test.b as b
File "test/b.py", line 1, in <module>
import test.a as a
AttributeError: module 'test' has no attribute 'a'
But when I change it to from test import a
and from test import b
, it works fine.
So what is the difference?
I am using python3.5
Edit 1:
As asked by @Davis Herring, python2 behaves differently.
when using import test.a as a
format there is no error thrown.
Python 2.7.12 (default, Dec 4 2017, 14:50:18)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import test.a
However, when using from test import a
it throws error
Python 2.7.12 (default, Dec 4 2017, 14:50:18)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import test.a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "test/a.py", line 2, in <module>
from test import b
File "test/b.py", line 1, in <module>
from test import a
ImportError: cannot import name a