Lesson 08 – Understanding __init__.py¶
Prerequisites: Complete Lesson 07 – Environment Variables and .env Files to understand how configuration data may be loaded as packages initialize.
Python uses the __init__.py file to mark a directory as a package. This file can be empty, but it's often used to control what gets imported when you use from package import * and to run package initialization code.
1. Why __init__.py Exists¶
Before Python 3.3, a directory without an __init__.py file could not be imported as a module. The presence of this file signaled to the interpreter that the directory should be treated as a package. Even though modern Python no longer requires it for namespace packages, adding __init__.py keeps your package structure explicit and compatible with older tooling.
2. Common Uses¶
- Initializing Package State: You can execute setup logic like loading configuration data or setting package-level variables.
- Controlling Imports: By defining the
__all__list, you specify which modules or attributes get imported when users runfrom package import *. - Aggregating Submodules: Import submodules inside
__init__.pyso they are available directly from the package, e.g.,package.module.
# Inside mypackage/__init__.py
from .utilities import helper
__all__ = ["helper"]
3. Keeping It Lightweight¶
Avoid heavy computations or side effects inside __init__.py. Doing too much can slow down imports and lead to unexpected behavior. Use it for lightweight setup and leave complex logic in separate modules.
Key Takeaways¶
__init__.pymakes a directory a package and can run initialization code.- Define
__all__to control wildcard imports and re-export submodules. - Keep the file simple to avoid slowing down package imports.
Next Up¶
Shift from backend structure to user experience in Lesson 09 – AJAX for Dynamic Pages.