Packages & Initialization
As your project grows, having 50 modules in one folder becomes chaotic. A Package is simply a directory that contains multiple modules. Packages allow you to organize code hierarchically (e.g., app.models, app.views, app.utils).
1. Creating a Package Structure
Section titled “1. Creating a Package Structure”A directory is treated as a package if it contains a file named __init__.py.
Directorymy_project/
- main.py
Directoryutils/
- init .py
- networking.py
- validation.py
The __init__.py File
Section titled “The __init__.py File”This file is executed the first time any part of the package is imported.
- Exposing API: You can use it to “pull up” names from submodules so the user can import them more easily.
- Initialization: Set up package-wide configuration or logging.
- The
__all__Variable: Defines exactly what is exported when a user doesfrom package import *.
# Expose 'send_request' directly as 'utils.send_request'from .networking import send_request
__all__ = ["send_request"]2. Namespace Packages (Python 3.3+)
Section titled “2. Namespace Packages (Python 3.3+)”Since Python 3.3, you can create Namespace Packages—directories that are treated as packages even without an __init__.py file.
- Regular Packages: Require
__init__.py. Good for single-author projects. - Namespace Packages: Allow you to spread a single package across multiple physical directories on your disk. This is a very advanced feature used by large organizations (like Google) to manage massive monorepos.
3. Relative vs. Absolute Imports
Section titled “3. Relative vs. Absolute Imports”Inside a package, modules need to talk to each other.
Absolute Imports (Preferred)
Section titled “Absolute Imports (Preferred)”Starts from the project root. Clear and unambiguous.
from my_app.utils.networking import sendRelative Imports
Section titled “Relative Imports”Uses “dots” to represent the current or parent directory.
.(this directory)..(parent directory)
from .networking import send # Sibling modulefrom ..models import User # Parent module4. Sub-packages
Section titled “4. Sub-packages”Packages can contain other packages, creating deep hierarchies.
import scipy.stats.distributions# scipy = Package# stats = Sub-package# distributions = Module5. Summary Table
Section titled “5. Summary Table”| Concept | Meaning |
|---|---|
| Module | A single .py file. |
| Package | A directory containing modules and an __init__.py. |
| Sub-package | A package inside another package. |
| Dot Notation | Used to traverse the hierarchy (p.sub_p.mod). |
__init__.py | The constructor for the package. |