I'm working in Python 2.7.
This is my folder structure. (temp
is already added to this system path.)
temp
|
|--main.py
|
|--sub
|
|--__init__.py
|
|--sub2
|
|--__init__.py
|
|--square.py
The file contents are listed below.
main.py:
import sub.sub2 as sub2
sub2.run()
sub/__init__.py: empty
sub/sub2/__init__.py:
import sub.sub2.square as square
def run():
square.square_it(3)
sub/sub2/square.py:
def square_it(x): return x**2
When I execute main.py
, I receive the following error (ignore the line numbers):
Traceback (most recent call last):
File "main.py", line 3, in <module>
import sub.sub2 as sub2
File "/home/gimlisonofgloin1/temp/sub/sub2/__init__.py", line 3, in <module>
import sub.sub2.square as square
AttributeError: 'module' object has no attribute 'sub2'
I can fix this by changing the statement in which the error occurs to any of these statements (in the final three listed solutions, I have to change the function call appropriately, of course):
from sub.sub2 import square as square
;from sub.sub2.square import square_it
;from .square import square_it
(as pointed out kindly in user NeErAj KuMaR's answer); orimport sub.sub2.square
.
My question is: why does the original line of code yield an error, even though it is semantically equivalent to the working ("fixed") lines of code (in particular, the 1st and 4th solutions listed)?
In attempting to answer this question, I have stumbled across this bit of text from the Python 2.0 Reference Manual:
To avoid confusion, you cannot import sub-modules 'as' a different local name. So 'import module as m' is legal, but 'import module.submod as s' is not. The latter should be written as 'from module import submod as s', see below.
This is consistent with the errors I'm receiving. However, this (seemingly important) little blurb is not present anywhere in the Python 2.7 Reference Manual. Is that little blurb from the Python 2.0 reference still applicable in Python 2.7? Or am I getting this error for a completely different reason that I'm not aware of?