Python theorytheory 0/50 · 0%
Tooling · hard

40. Structuring larger programs: packages and __init__.py

Organizing modules into packages.

A directory containing an `__init__.py` (even an empty one) is a package, letting you organize related modules under a shared namespace.

python
# mypackage/__init__.py
from .wallet import Wallet
from .chain import ChainClient

# usage elsewhere:
from mypackage import Wallet

Relative imports (`from .module import name`) reference siblings within the same package; absolute imports reference the full dotted path from the project root. Since Python 3.3, "namespace packages" can technically omit `__init__.py`, but including it explicitly remains common for clarity and to control the package's public API via `__all__`.

Check your understanding

  1. 1. What file traditionally marks a directory as a Python package?

  2. 2. What does `from .wallet import Wallet` use?

  3. 3. What does `__all__` control in a package's __init__.py?