The difference between having _init_.py and not having one in your module directory is:
When you have __init__.py
(blank one), you can import the module using
from dirname import MyModule
But when you dont have _init_.py at all, you cannot import the module without adding the path till that module to PYTHONPATH. In this case from dirname import MyModule
FAILS, or reports error.
# Structure of directory/Module without _init_.py
[root@Machine python]# cd NoInitModule/
[root@Machine NoInitModule]# pwd
/python/NoInitModule
[root@Machine NoInitModule]# ls -l
total 4
-rw-r--r--. 1 root root 44 Jan 16 07:02 ModuleX.py
# Structure of directory/Module with _init_.py
[root@Machine NoInitModule]# cd ../InitModule/
[root@Machine InitModule]# ls -l
total 4
-rw-r--r--. 1 root root 0 Jan 16 07:13 __init__.py
-rw-r--r--. 1 root root 49 Jan 16 07:12 ModuleY.py
[root@Machine InitModule]#
Examples:
# NO _init_.py, from dir import module statement - DOESN'T WORK
[root@Machine python]# cat impomod.py
from NoInitModule import ModuleX
ModuleX.printBye()
[root@Machine python]# python impomod.py
Traceback (most recent call last):
File "impomod.py", line 7, in <module>
from NoInitModule import ModuleX
ImportError: No module named NoInitModule
[root@Machine python]#
# NO _init_.py, import statement - DOESN'T WORK
[root@Machine python]# vim impomod.py
[root@Machine python]# cat impomod.py
#from NoInitModule import ModuleX
import ModuleX
ModuleX.printBye()
[root@Machine python]# python impomod.py
Traceback (most recent call last):
File "impomod.py", line 8, in <module>
import ModuleX
ImportError: No module named ModuleX
[root@Machine python]#
# NO _init_.py, INSERT path in PYTHONPATH, import module statement after inserting path - WORKS
[root@Machine python]# vim impomod.py
[root@Machine python]# cat impomod.py
import sys
sys.path.append('/python/NoInitModule')
print sys.path
import ModuleX
ModuleX.printBye()
[root@Machine python]# python impomod.py
Bye from Module X with no __init__.py
[root@Machine python]#
# HAVING _init_.py, No INSERT of path, from dir import module statement - WORKS
[root@Machine python]# cat impXmod.py
import sys
from InitModule import ModuleY
ModuleY.printSeeU()
[root@Machine python]#
[root@Machine python]# python impXmod.py
See you from Module Y having __init__.py
# HAVING _init_.py, No INSERT of path, import module statement - DOESN'T WORK
[root@Machine python]# vim impXmod.py
[root@Machine python]# cat impXmod.py
import sys
#from InitModule import ModuleY
import ModuleY
ModuleY.printSeeU()
[root@Machine python]# python impXmod.py
Traceback (most recent call last):
File "impXmod.py", line 3, in <module>
import ModuleY
ImportError: No module named ModuleY
Ofcourse, subfolders issue can be added to this