Objective

Organize Python code into modules and packages, control the public API with __all__, and understand the import system.

Tools & Technologies

  • import
  • from
  • __init__.py
  • __all__
  • importlib
  • packages

Key Commands

from pathlib import Path
import mypackage.utils
from . import helper
__all__ = ['MyClass']

Architecture Overview

graph TD subgraph Package Structure PKG[mypackage/] --> INIT[__init__.py] PKG --> UTILS[utils.py] PKG --> MODELS[models.py] PKG --> SUB[subpackage/] SUB --> SINIT[__init__.py] SUB --> SMOD[core.py] end MAIN[main.py] -->|import mypackage.utils| UTILS MAIN -->|from mypackage import MyClass| INIT style PKG fill:#1a1a2e,stroke:#00d4ff,color:#e0e0e0

Step-by-Step Process

01
Import Styles

Different ways to import modules.

# Standard imports
import os
import sys
from pathlib import Path
from datetime import datetime, timedelta

# Alias
import numpy as np
import pandas as pd

# Import everything (avoid in production)
from math import *

# Conditional import
try:
    import ujson as json
except ImportError:
    import json
02
Create a Package

Organize code into a package with __init__.py.

# Structure:
# myapp/
#   __init__.py
#   config.py
#   utils.py

# myapp/__init__.py
from .utils import format_date, parse_config
from .config import Settings
__all__ = ['format_date', 'parse_config', 'Settings']

# Usage:
from myapp import format_date
from myapp.utils import parse_config

Challenges & Solutions

  • Circular imports cause ImportError — restructure to avoid mutual dependencies
  • from module import * pollutes namespace and makes it hard to find where names come from

Key Takeaways

  • __all__ controls what 'from module import *' exports
  • Relative imports (from . import x) only work inside packages