Sub topic 1
Packaging and Publishing a Python Library
Prerequisites
Assume you can write and import Python modules, use a virtual environment and pip, and run basic command-line commands.
Laying out a library: why the `src` layout
A src layout keeps the importable package separate from project files and tests. This helps tests use the installed package instead of accidentally importing files from the working directory.
greeter/
├── pyproject.toml
├── README.md
├── LICENSE
├── src/
│ └── greeter/
│ ├── __init__.py
│ └── py.typed
└── tests/
└── test_greet.py`pyproject.toml`: one file that describes the project
pyproject.toml is the standard configuration file for Python packaging. It identifies the build backend and stores project metadata.
[build-system]
requires = ["setuptools>=77"]
build-backend = "setuptools.build_meta"
[project]
name = "greeter"
version = "0.1.0"
description = "A tiny greeting library."
readme = "README.md"
requires-python = ">=3.9"
license = "MIT"
license-files = ["LICENSE"]
dependencies = []The build-system table tells a build frontend which backend to use. The project table describes the package for tools such as pip and PyPI.
Build frontends and backends
A build frontend coordinates a build. The backend performs the project-specific work. python -m build creates both a source distribution and a wheel by reading pyproject.toml.
python -m pip install build
python -m buildThe resulting files appear in dist/.
Describing your project
The package name must be unique on PyPI. The version identifies a release. requires-python prevents installation on unsupported Python versions. The readme, license, and description help users evaluate the package.
| Field | Purpose |
|---|---|
| `name` | Distribution name used by installers |
| `version` | Release identifier |
| `requires-python` | Supported Python versions |
Declaring dependencies and optional extras
Put libraries required at runtime in dependencies. Put development or feature-specific requirements in optional extras.
[project.optional-dependencies]
test = ["pytest"]
[project.scripts]
greeter = "greeter.cli:main"Users can install the test tools with pip install "greeter[test]". The project.scripts entry creates a command-line executable.
Exercise
Why can a src layout reveal packaging mistakes that a flat layout hides?
Show answer
Tests cannot accidentally import the package directly from the project root, so missing package files or incorrect build configuration become visible.