Why is there a difference between 'import ...' and 'from ... import ...' and why do I get an exception using the first one?
Here is my layout:
/tmp/zero/
|~two/
| |-__init__.py
| |-four.py
| `-three.py
|-__init__.py
`-one.py
/tmp/zero/one.py
=================
import zero.two
/tmp/zero/two/__init__.py
=================
import zero.two.three
/tmp/zero/two/three.py
=================
# this works
from zero.two import four
four.myprint()
# this FAILS
import zero.two.four
zero.two.four.myprint()
/tmp/zero/two/four.py
=================
def myprint():
print 'four.myprint'
/tmp$ PYTHONPATH=/tmp/ python -c 'import zero.one'
four.myprint
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "zero/one.py", line 1, in <module>
import zero.two
File "zero/two/__init__.py", line 1, in <module>
import zero.two.three
File "zero/two/three.py", line 9, in <module>
zero.two.four.myprint()
AttributeError: 'module' object has no attribute 'two'
zero.two
is a module there,zero/two/__init__.py
. It's a concrete thing, not a magic thing. If you put intozero/two/__init__.py
a linefrom . import four
, it'll start working.os.path
is an example of this - it's a module, but it's imported inos/__init__.py
so that you canimport os; os.path
.