GGistDev

Modules and Packages in Python

Modules are Python files; packages are directories with modules. Imports load names into a module’s namespace.

Modules and imports

# file: mathutil.py
PI = 3.14159

def area(r: float) -> float:
    return PI * r * r

Use imports to access.

import mathutil
from mathutil import area, PI
import mathutil as mu

Packages

A package is a directory containing modules (and optionally __init__.py).

mypkg/
  __init__.py
  core.py
  util.py

Initialize or re‑export in __init__.py.

# mypkg/__init__.py
from .core import run

Absolute vs relative imports

Absolute imports are clearer; use relative for intra‑package references.

from mypkg import util       # absolute
from . import util           # relative (within package)
from ..shared import common  # up one level

Import search path

Modules are resolved via sys.modules cache, the current package, and sys.path entries (including the project and site‑packages).

Namespaces and aliasing

Aliasing helps avoid conflicts and improve readability.

import numpy as np

Executable modules

Run a module as a script with -m.

python -m mypkg.core

Packaging basics

Use pyproject.toml to define metadata and dependencies. Build with pip build/pip install -e . for editable installs.

Summary

  • Modules are files; packages are directories—imports populate namespaces
  • Prefer absolute imports; use relative for intra‑package references
  • Use -m to run modules; package with pyproject.toml for distribution