Chapter 9 of 21
Dictionaries & Sets
Current Study Module
Modules, Packages & Pip
File I/O & Serialization
Chapter 08 • Modular Architecture

Modules, Packages, Pip & pyproject.toml

Monolithic single-file scripts become unmaintainable as systems scale. Learn how Python resolves imports through sys.path, how packages encapsulate namespaces with __init__.py, why if __name__ == '__main__' is required, and how to package applications using the modern pyproject.toml standard.

1. Modules vs Packages

  • Module: Any single Python file containing code (e.g., database.py).
  • Package: A directory containing one or more modules along with an __init__.py file, representing a hierarchically organized namespace.
# Typical enterprise package structure:
my_service/
├── pyproject.toml            # Project metadata & build dependencies
├── src/
│   └── my_service/
│       ├── __init__.py       # Package initialization & public API exports
│       ├── core.py           # Core business logic module
│       └── utils/
│           ├── __init__.py
│           └── crypto.py     # Submodule: my_service.utils.crypto

2. How the Python Import System Resolves Files

When you execute import payment, Python executes a multi-step resolution process:

  1. Cache Check: Checks sys.modules. If already imported, it returns the cached module instantly.
  2. Search sys.path: Searches the directories listed in sys.path in order:
    • The directory of the running script.
    • The PYTHONPATH environment variable directories.
    • Standard library built-ins (e.g. math, sys).
    • Site-packages in the active virtual environment (third-party pip packages).
  3. Bytecode Execution: Compiles and executes top-level statements in the module, storing the result in sys.modules.

3. Understanding "if __name__ == '__main__'"

Every module in Python has a special internal attribute named __name__:

  • If the file is executed directly via terminal (python script.py), Python sets __name__ = "__main__".
  • If the file is imported by another script (import script), Python sets __name__ = "script".
def calculate_shipping(weight_kg: float) -> float:
    return round(weight_kg * 4.50, 2)

# Prevent test executions from running when imported into another file!
if __name__ == "__main__":
    print("Running standalone local test:")
    print("Test shipping for 10kg:", calculate_shipping(10))

4. Modern Packaging Standard: pyproject.toml (PEP 621)

Legacy Python projects used complex, executable setup.py scripts. Modern standards define declarative metadata in a single pyproject.toml:

# pyproject.toml
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "hifi-analytics"
version = "1.0.0"
description = "High-performance enterprise analytics toolkit"
readme = "README.md"
requires-python = ">=3.10"
dependencies = [
    "pydantic>=2.7.0",
    "httpx>=0.27.0"
]

[project.scripts]
hifi-cli = "hifi_analytics.cli:main"

Explore Related Tools

Hand-picked utilities and calculators related to this tool.

Related Tools