As programs grow, you split code across modules (single files) and packages (directories of modules). This chapter covers how Python finds, loads, and organizes code.

Modules

Any .py file is a module:

  # math_utils.py
PI = 3.14159

def circle_area(radius):
    return PI * radius ** 2
  
  # main.py
import math_utils

print(math_utils.circle_area(5))

from math_utils import circle_area, PI
print(circle_area(3))
  

Import Styles

  import os                          # import module
from os import path                # import specific name
from os import path as os_path     # import with alias
from os import *                   # avoid — pollutes namespace
  

Packages

A package is a directory containing an __init__.py file:

  myproject/
├── main.py
└── mypackage/
    ├── __init__.py
    ├── models.py
    ├── utils.py
    └── services/
        ├── __init__.py
        └── api.py
  
  # mypackage/__init__.py
from .models import User
from .utils import format_date

__all__ = ["User", "format_date"]
  
  # main.py
from mypackage import User
from mypackage.services.api import fetch_data
  

Relative Imports

Inside a package, use relative imports:

  # mypackage/services/api.py
from ..models import User       # up one level
from . import helpers           # same package
  

Relative imports only work inside packages, not in top-level scripts.

__name__ and __main__

  # utils.py
def helper():
    return "help"

if __name__ == "__main__":
    # Runs only when executed directly: python utils.py
    print(helper())
  

When imported, __name__ is the module name. When run directly, it’s "__main__".

The Python Path

Python searches for modules in:

  1. Current directory
  2. Directories in PYTHONPATH environment variable
  3. Standard library
  4. Site-packages (installed packages)
  import sys
print(sys.path)  # list of search directories
  

Installing Third-Party Packages

  pip install requests
  
  import requests
response = requests.get("https://api.github.com")
  

Packages install into site-packages and become importable globally (within that virtual environment).

Standard Library Highlights

Module Purpose
os, sys Operating system interfaces
pathlib Object-oriented file paths
json JSON serialization
datetime Dates and times
collections Specialized containers
itertools Iterator tools
functools Higher-order functions
re Regular expressions
logging Logging framework
argparse CLI argument parsing
unittest Testing framework
  from pathlib import Path
from datetime import datetime, timedelta

config = Path.home() / ".myapp" / "config.json"
deadline = datetime.now() + timedelta(days=7)
  

Project Structure Best Practices

  myapp/
├── pyproject.toml
├── README.md
├── src/
│   └── myapp/
│       ├── __init__.py
│       ├── main.py
│       ├── models/
│       ├── services/
│       └── utils/
└── tests/
    └── test_models.py
  
  • Keep business logic out of main.py
  • One class or related group per module
  • Use src/ layout for installable packages

Well-organized modules and packages are the foundation of every professional Python project.