__init__.py
in Python PackagesNote: Since Python 3.3 (as per PEP 420), a directory can be treated as a package even without an __init__.py
file. These are called implicit namespace packages. However, for most practical purposes, especially when initialization or import control is needed, it’s still best to include __init__.py
.
The __init__.py
file is a special Python file used to mark a directory as a package. In older Python versions, this file was required for any directory to be importable as a package.
__init__.py
my_package/
├── __init__.py
├── module1.py
└── module2.py
When you run:
import my_package
The code inside __init__.py
will run.
__init__.py
Even an empty __init__.py
file is sufficient to turn a directory into a recognized package.
# Inside __init__.py
from .module1 import function1
from .module2 import function2
This allows:
from my_package import function1, function2
# Inside __init__.py
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.info("my_package initialized")
# Inside __init__.py
__version__ = "1.0.0"
AUTHOR = "Sai Krishna"
# Inside __init__.py
PI = 3.14159
APP_NAME = "DataProcessor"
Explicit Namespace Package:
__init__.py
file.analytics/
├── __init__.py
├── summary.py
└── stats.py
Usage:
from analytics import stats
Implicit Namespace Package (Python 3.3+ only):
__init__.py
file is needed.# Directory structure (no __init__.py)
project-root/
├── analytics/
│ └── stats/
│ └── summary.py
└── another-location/
└── analytics/
└── data/
└── raw.py
Both analytics.stats
and analytics.data
can be imported as part of the same namespace:
from analytics.stats import summary
from analytics.data import raw
This is possible because they are part of a common implicit namespace package.
__init__.py
Required?import my_package
print(dir(my_package))
This will show the attributes, including those defined in __init__.py
.
The __init__.py
file helps define a package's structure and behavior. Even in modern Python versions, it’s a best practice to include it for clarity, control, and compatibility.