What is the purpose of `__init__.py` in Python packages?
`__init__.py` marks a directory as a Python package. It can also execute initialization code and define what is accessible when the package is imported.
__init__.py
plays a critical role in Python packages, serving as an indicator to Python that the directory should be treated as a package. This allows for the organization of related modules and sub-packages within a single namespace. An __init__.py
file can be empty, which is sufficient to define a package, but you can also include initialization code that executes when the package is imported. This might include setting up package-level variables, importing submodules, or defining the public API by specifying which modules or functions should be accessible. For example:
from .module1 import func1
from .module2 import func2
__all__ = ['func1', 'func2']
By defining the __all__
variable, you control what is imported when using the wildcard import statement (e.g., from package import *
). This helps maintain clean and manageable namespaces. Overall, __init__.py
is an essential component for structuring Python packages effectively.