Reputation: 8297
In python, a directory containing one or more modules sometimes has __init__.py
, so that the directory can be treated as a python package
, is this correct? What differences the __init__
makes? (also another Q, is a python module just a python code-file with related and possibly independent (to other files) set of classes, functions and variables?)
Upvotes: 0
Views: 125
Reputation: 799150
In addition, the contents of __init__.py
becomes the contents of the package when treated as a module, i.e. the contents of somepackage/__init__.py
will be found in dir(somepackage)
when you import somepackage
.
Modules themselves can be Python code, specially-crafted C code, or they could be an artificial construct injected by the executable that loads the Python VM.
Upvotes: 2
Reputation: 500713
Here's an explanation for why __init__.py
is needed:
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 asstring
, from unintentionally hiding valid modules that occur later 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.
As I've just recommended to another poster, the tutorial on modules is pretty informative.
Upvotes: 4