Python › Modules & Packaging

What does the __init__.py file do inside a package directory?

Beginner

Answer

__init__.py marks a directory as a regular Python package and runs when the package is first imported, letting you control what's exposed at the package level (e.g., re-exporting submodule contents), set up package-wide state, or simply exist as an empty file to establish the package structure. Since Python 3.3, packages can technically work without it (namespace packages), but explicit __init__.py remains the common convention.
# mypackage/__init__.py
from .models import User
from .utils import helper

__all__ = ['User', 'helper']

# now: from mypackage import User
Real-world example A library's __init__.py re-exports key classes from internal submodules so users write `from mylib import Client` instead of the longer `from mylib.core.client import Client`.

Common follow-ups: What is __all__ and how does it affect `from package import *`?;What are namespace packages and how do they differ?