I have been reading about the function of __init__.py
file. It is said that we need an empty __init__.py
file in the folder which contains modules, so that these modules can be imported. However, I tried adding a folder path to PYTHONPATH (Environment Variable in Windows 7). Although this folder does not contain an __init__.py
file, I can still import the modules from that folder. Could you please explain how these modules can be imported without the existence of an __init__.py
?
Thanks,
Best regards
Yes, this works, as you can tell. The reason for the empty
__init__.py
file is to mark sub-folders as folders containing modules.So a folder in PYTHONPATH is ok to have modules in it, but any subfolders of those folders have to have a
__init__.py
file in them to be able to import modules from them.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 usingBut 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
# Structure of directory/Module with _init_.py
Examples:
# NO _init_.py, from dir import module statement - DOESN'T WORK
# NO _init_.py, import statement - DOESN'T WORK
# NO _init_.py, INSERT path in PYTHONPATH, import module statement after inserting path - WORKS
# HAVING _init_.py, No INSERT of path, from dir import module statement - WORKS
# HAVING _init_.py, No INSERT of path, import module statement - DOESN'T WORK
Ofcourse, subfolders issue can be added to this
If a directory (folder) contains a
__init__.py
file then it becomes a package. What you thought you read was not strictly correct, as you found. A package can be imported as if it was a module by itself, and any code in__init__.py
is run, although it is often empty. Packages are a way of grouping multiple modules together, and you can load them using:Packages can also be nested, and often are. Look in the Lib directory under your Python software directory for many examples.
__init__.py
turns a folder into a package. This is useful to create a sort of hierarchy of modules, where you can have import-statements like this:This is not possible without packages.