Packaging & Environments
Modules and packages, how imports are resolved, virtual environments, pip and lock files, pyproject.toml, uv and Poetry, building and publishing wheels, project layout, and tooling (ruff, pytest, pre-commit).
Python's packaging story was famously messy, but it has converged: pyproject.toml for configuration, virtual environments for isolation, wheels for distribution, and fast modern tools like uv. This lesson explains how the pieces fit.
Modules and packages
- A module is a
.pyfile.import math_utilsrunsmath_utils.pyonce and caches it insys.modules. - A package is a directory of modules, normally with an
__init__.py(which runs when the package is imported).
myapp/
├── __init__.py
├── cli.py
├── core/
│ ├── __init__.py
│ └── pricing.py
└── utils.pyimport myapp.core.pricing
from myapp.core import pricing
from myapp.core.pricing import calculate_total
from . import utils # relative import (inside the package only)
from ..utils import slugifyHow imports are resolved
import x searches the locations in sys.path, in order:
- The directory of the script being run (or the current directory for
python -mand the REPL). PYTHONPATHentries.- The standard library.
- site-packages of the active environment — where pip installs packages.
Run code inside a package as a module so imports work: python -m myapp.cli, not python myapp/cli.py.
Circular imports
If a.py imports b and b.py imports a, one of them sees a partially initialised module ("cannot import name X from partially initialized module"). Fixes: move shared code into a third module, import inside the function that needs it, or import the module rather than names from it (import a, then use a.thing later).
Virtual environments
Every project should have its own environment, so its dependencies (and versions) don't conflict with other projects or the system Python.
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install requests==2.32.3
pip freeze > requirements.txt # pin exact versions
deactivateA venv is just a directory with a Python executable link and its own site-packages. Never sudo pip install into the system Python.
pyproject.toml
The single standard configuration file for a project (PEP 621):
[project]
name = "acme-pricing"
version = "1.4.0"
description = "Pricing engine"
readme = "README.md"
requires-python = ">=3.11"
dependencies = [
"httpx>=0.27",
"pydantic>=2.6,<3",
]
[project.optional-dependencies]
postgres = ["psycopg[binary]>=3.1"]
[project.scripts]
acme-price = "acme_pricing.cli:main" # installs a command-line entry point
[dependency-groups]
dev = ["pytest>=8", "ruff", "mypy"]
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.ruff]
line-length = 100
[tool.pytest.ini_options]
testpaths = ["tests"]- Dependencies in
pyproject.tomlare ranges (what your code is compatible with). - A lock file pins the exact versions (and hashes) of everything, including transitive dependencies, so every install is reproducible.
Tools
| Tool | What it does |
|---|---|
| pip | Installs packages; the baseline |
| uv (Astral) | Extremely fast all-in-one: Python version management, venvs, dependency resolution, lock files (uv.lock), running tools — written in Rust |
| Poetry | Dependency management + lock file + build/publish |
| pip-tools | pip-compile turns ranges into a pinned requirements.txt |
pipx / uv tool | Install CLI tools in isolated environments |
| conda | Environments with non-Python binaries (CUDA, MKL); popular in data science |
A modern workflow with uv:
uv init acme-pricing && cd acme-pricing # creates pyproject.toml, .python-version
uv add httpx pydantic # adds to pyproject, updates uv.lock, syncs .venv
uv add --dev pytest ruff mypy
uv run pytest # runs inside the project environment
uv run python -m acme_pricing.cli
uv sync --frozen # CI: install exactly what's locked
uv python install 3.13 # manage interpreter versionsProject layout: the src layout
acme-pricing/
├── pyproject.toml
├── uv.lock
├── README.md
├── src/
│ └── acme_pricing/
│ ├── __init__.py
│ ├── cli.py
│ └── engine.py
└── tests/
└── test_engine.pyPutting code under src/ forces tests to import the installed package rather than accidentally importing from the working directory — catching packaging mistakes early.
Building and publishing
A wheel (.whl) is a pre-built, zip-format package that installs by copying files — fast, no build step on the user's machine. Pure-Python wheels work everywhere (py3-none-any); wheels with compiled extensions are built per platform and Python version (cp312-cp312-manylinux_x86_64). An sdist (.tar.gz) is the source distribution, built on install if no wheel matches.
uv build # or: python -m build → dist/*.whl and dist/*.tar.gz
uv publish # or: twine upload dist/* → PyPIUse trusted publishing from CI (OIDC) rather than long-lived API tokens.
Code quality tooling
ruff check . --fix # linting (replaces flake8, isort, pyupgrade…), very fast
ruff format . # formatting (black-compatible)
mypy src/ # type checking (or pyright)
pytest -q # testsWire them into pre-commit hooks and CI so every change is checked automatically.
# tests/test_engine.py
import pytest
from acme_pricing.engine import total
@pytest.mark.parametrize("items, expected", [([], 0), ([100, 250], 350)])
def test_total(items, expected):
assert total(items) == expected
def test_negative_price_rejected():
with pytest.raises(ValueError):
total([-1])Docker tip
FROM python:3.13-slim
COPY --from=ghcr.io/astral-sh/uv:latest /uv /bin/uv
WORKDIR /app
COPY pyproject.toml uv.lock ./
RUN uv sync --frozen --no-dev --no-install-project # dependencies layer (cached)
COPY src ./src
RUN uv sync --frozen --no-dev
CMD ["uv", "run", "--no-sync", "python", "-m", "acme_pricing.cli"]- Modules are files, packages are directories; imports search sys.path and are cached in sys.modules.
- Don't shadow stdlib names; run package code with python -m; break circular imports.
- One virtual environment per project; never install into the system Python.
- pyproject.toml declares metadata, dependency ranges and tool config; lock files pin exact versions.
- uv is the fast modern all-in-one tool; Poetry and pip-tools are alternatives.
- Use the src layout, build wheels, and automate ruff, mypy and pytest in CI.