The __init__.py file serves several important purposes in a Python package:
-
Package Initialization: It is executed when the package is imported, allowing you to run initialization code for the package. This can include setting up variables, importing submodules, or configuring package-level settings.
-
Indicating a Package: The presence of
__init__.pyin a directory tells Python that the directory should be treated as a package. Without this file, Python will not recognize the directory as a package, and you won't be able to import modules from it. -
Controlling Exports: You can define an
__all__list within__init__.pyto specify which modules or symbols should be exported when usingfrom package import *. This helps control what is accessible to users of the package. -
Relative Imports: It allows for relative imports within the package. You can import submodules using dot notation, which helps maintain a clear structure.
Here’s a simple example of an __init__.py file:
# my_package/__init__.py
# Importing submodules
from .module1 import *
from .module2 import *
# Defining what to export
__all__ = ['module1', 'module2']
In this example, when my_package is imported, module1 and module2 are also imported, and only those modules will be accessible when using from my_package import *.
