Reputation: 115
I'm creating a big variety of programs and because of this I need lots of different packages and modules. Some of them I've written myself and some are downloaded.
The downloaded modules all have __init__.py
files in their main directorys and somewhere random in the sub-directorys. Here is an example:
/theexamplemodule
|-__init__.py #first
|-file1.py
|-file2.py
|-folder1
| |-__init__.py #second
| |-file3.py
|-folder2
| |-data.txt
| |-file4.py
I've searched around on stackverflow and I found this 'What is __init__.py for?' answer why the first one is there, it sets the directorys as modules or some thing like that...
But why is this declaration nessecary and what is the sence of the others?
My own modules are build similar to this but without the __init__.py
files. I don't get the advantages of the __init__.py
files. What are those advantages?
Upvotes: 1
Views: 156
Reputation: 76
"The init.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later (deeper) on the module search path. In the simplest case, init.py can just be an empty file, but it can also execute initialization code for the package or set the all variable, described later."
Files named init.py are used to mark directories on disk as a Python package directories. If you have the files
mydir/spam/__init__.py
mydir/spam/module.py
and mydir is on your path, you can import the code in module.py as:
import spam.module or
from spam import module If you remove the init.py file, Python will no longer look for submodules inside that directory, so attempts to import the module will fail.
The init.py file is usually empty, but can be used to export selected portions of the package under more convenient names, hold convenience functions, etc. Given the example above, the contents of the init module can be accessed as import spam
Upvotes: 3