Use __init__.py inside a directory to mark it as a regular Python package, run package-level initialization code upon import, and control which submodules or symbols are exposed in the package’s public namespace.
Basic Example
Consider the following directory layout:
analytics/
├── __init__.py
├── cleaning.py
└── metrics.py
# analytics/metrics.py
def calculate_mean(values: list[float]) -> float:
return sum(values) / len(values)
# analytics/__init__.py
from .metrics import calculate_mean
__version__ = "1.0.0"
__all__ = ["calculate_mean", "__version__"]
# main.py (external script)
import analytics
# Accessible directly at the package level thanks to __init__.py
print(analytics.calculate_mean([10, 20, 30])) # Output: 20.0
print(analytics.__version__) # Output: 1.0.0
Key Details & Responsibilities
- Defining the public API (
__all__and re-exports): Without re-exporting symbols in__init__.py, callers must know your internal file structure (from analytics.metrics import calculate_mean). Importing key functions into__init__.pylets you refactor internal submodules later without breaking external imports, while__all__controls whatfrom analytics import *exports. - Package-level initialization: Python executes
__init__.pyonce—the first time the package or any submodule inside it is imported—and caches the module insys.modules. This makes it useful for setting up package loggers, loading configuration defaults, or exposing metadata like__version__. - Regular packages vs. Namespace packages (PEP 420): Since Python 3.3, a folder without an
__init__.pyfile is still importable as an implicit namespace package (designed for splitting a single package across multiple directories or repositories). However, including an empty__init__.pyis still standard practice for regular packages because it makes package boundaries explicit, avoids accidental directory shadowing, and ensures compatibility with test runners (pytest) and build tools. - Keep
__init__.pylightweight: Avoid putting heavy computation, network requests, or slow I/O inside__init__.py, because importing even a tiny utility submodule (import analytics.cleaning) triggers execution of the parent package’s__init__.pyfirst.
Regular Package (__init__.py) vs. Namespace Package (No __init__.py)
| Feature | Regular Package (With __init__.py) |
Implicit Namespace Package (PEP 420) |
|---|---|---|
| Package initialization code | Supported (runs on first import) | Not supported |
Custom public namespace / __all__ |
Supported via re-exports in __init__.py |
Not supported at root level |
| Multi-directory spanning | Single directory only | Can span multiple paths on sys.path |
Tooling & pytest discovery |
Explicitly recognized as a package root | Can cause import/naming collisions if sibling folders share names |
You must log in or register to comment.
