Skip to content

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).


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

This file is executed the first time any part of the package is imported.

  1. Exposing API: You can use it to “pull up” names from submodules so the user can import them more easily.
  2. Initialization: Set up package-wide configuration or logging.
  3. The __all__ Variable: Defines exactly what is exported when a user does from package import *.
utils/__init__.py
# Expose 'send_request' directly as 'utils.send_request'
from .networking import send_request
__all__ = ["send_request"]

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.

Inside a package, modules need to talk to each other.

Starts from the project root. Clear and unambiguous.

from my_app.utils.networking import send

Uses “dots” to represent the current or parent directory.

  • . (this directory)
  • .. (parent directory)
from .networking import send # Sibling module
from ..models import User # Parent module

Packages can contain other packages, creating deep hierarchies.

import scipy.stats.distributions
# scipy = Package
# stats = Sub-package
# distributions = Module

ConceptMeaning
ModuleA single .py file.
PackageA directory containing modules and an __init__.py.
Sub-packageA package inside another package.
Dot NotationUsed to traverse the hierarchy (p.sub_p.mod).
__init__.pyThe constructor for the package.