Lesson 46 of 52Real projects
Packaging and Publishing a Library
Build sdists and wheels, write metadata that resolvers trust, ship data files and type hints, and publish to PyPI with Trusted Publishing.
You wrote a slug helper that three teams now copy and paste between repos. Each copy has drifted, one has a bug fix the others lack, and nobody knows which is right. The fix is to turn it into a real package that anyone can install with uv add slug-kit and upgrade in one line. Packaging is also where libraries quietly hurt their users: an exact pin that blocks everyone's upgrades, a data file that is missing from the wheel, a release that installs on a Python it never supported. This lesson takes the pyproject.toml you met in Project Structure and turns it into something you can publish safely. It skips the lockfile anatomy covered in uv for Real Projects and goes further into what gets built and shipped.
Apps pin, libraries declare ranges
The single most important packaging rule is about dependencies, and it is different for apps and libraries.
An app (a web service, a CLI you deploy, a data pipeline) is the top of the tree. Nobody installs it next to other code, so you lock every package to an exact version with uv.lock and upgrade on purpose.
A library is installed into someone else's environment, next to dozens of other packages. A Python environment can hold only one version of each package, so the resolver must find a single version of requests that satisfies every library that asked for it. If your library says requests==2.31.0 and another says requests>=2.32, there is no answer and the install fails. Your user did nothing wrong and cannot fix it without forking you.
So libraries declare the widest range they actually support:
- Always a lower bound: the oldest version you test against, such as
httpx>=0.27. - An upper cap like
<3only when you have a real reason, for example a major version that is known to break you. Caps are debated among maintainers, because a cap you never revisit blocks users from upgrading for years. Many projects use lower bounds only and test against new releases in CI. - Never an exact pin (
==). That belongs in an app's lockfile.
The same applies to requires-python. Write >=3.12, never an upper bound like <3.15: resolvers treat that as a promise and may pick an ancient release of your library that had no cap, which is worse.
dependencies = ['pydantic==2.9.2']. What is the real-world problem?What gets built: sdist and wheel
uv build produces two files in dist/.
- An sdist (source distribution,
slug_kit-0.1.0.tar.gz) is your source code plus aPKG-INFOmetadata file. Installing it means running your build backend on the user's machine first. - A wheel (
slug_kit-0.1.0-py3-none-any.whl) is a zip file that is already laid out for installation. The installer unpacks it intosite-packages, writes the command-line scripts, and is done. No code of yours runs at install time. That is why wheels install in milliseconds, and why the oldsetup.py install, which executed arbitrary code, was retired.
The wheel filename is a contract. After the name and version come three tags: the Python implementation, the ABI (the compiled interface it was built against), and the platform. An installer only picks a wheel whose tags match the running interpreter.
Press Run (⌘ Enter) to see what happens.Read the four wheels top to bottom:
py3-none-any: pure Python, any Python 3, no compiled ABI, any platform. One wheel serves everyone. Most libraries you write look like this.cp314-cp314-manylinux_2_28_x86_64: compiled for CPython 3.14 on Linux with glibc 2.28 or newer.manylinuxis a promise that the binary only uses old, widely available system libraries.cp314t: thetmarks the free-threaded build of CPython. It has a different ABI, so it needs its own wheel.abi3: built against the stable ABI, so one wheel works on CPython 3.12 and every later version. Projects with C or Rust extensions use it to ship far fewer files.
If no wheel matches, the installer falls back to the sdist and tries to compile, which is where users see compiler errors. Shipping wheels for the common platforms (usually with cibuildwheel for compiled projects) is part of being a good maintainer.
Build frontends and backends
Building is split into two roles. The frontend is the command you run: uv build or python -m build. The backend is the library that knows how to turn your source tree into an sdist and a wheel. You choose it in [build-system], and the frontend installs it into a fresh, isolated environment before calling it.
| Backend | Good for |
|---|---|
uv_build | Pure-Python packages in a src/ layout. Fast, strict about layout, the default for uv init --lib. |
hatchling | Pure Python with more flexibility: plugins such as hatch-vcs for versions from Git tags. |
setuptools | The long-standing default. Needed for older projects and for C extensions built the classic way. |
flit-core | Minimal pure-Python packages. |
maturin, scikit-build-core | Rust and C/C++ extensions. |
uv reads [build-system] from pyproject.toml to learn which backend to use.
Before a release, run uv build --no-sources. It ignores any [tool.uv.sources] overrides (local paths, Git branches) that only work on your machine, so the build matches what any other frontend would produce.
Metadata that matters
Here is the full pyproject.toml for the library. Every line was checked with a real uv build.
[project]
name = "slug-kit"
version = "0.1.0"
description = "Turn titles into URL slugs"
readme = "README.md"
license = "MIT" # an SPDX expression (PEP 639)
license-files = ["LICENSE"]
authors = [{ name = "Ada Example", email = "ada@example.com" }]
requires-python = ">=3.12"
dependencies = ["text-unidecode>=1.3"]
classifiers = [
"Programming Language :: Python :: 3",
"Typing :: Typed",
]
[project.optional-dependencies] # extras: users opt in with slug-kit[cli]
cli = ["rich>=13"]
[project.scripts]
slugify = "slug_kit.cli:main"
[project.urls]
Source = "https://github.com/example/slug-kit"
Changelog = "https://github.com/example/slug-kit/releases"
[dependency-groups] # never published, for contributors only
dev = ["pytest>=8", "ruff"]
[build-system]
requires = ["uv_build>=0.11,<0.12"] # check the uv docs for the current range
build-backend = "uv_build"The fields people get wrong:
nameis normalised.Slug_Kit,slug.kitandslug-kitare the same project on PyPI, as the code above showed. The import name (slug_kit) is separate and cannot contain hyphens. Keep them obviously related.licenseis now a plain SPDX expression such as"MIT"or"Apache-2.0 OR MIT", withlicense-fileslisting the files to include. The oldlicense = { text = "..." }table and the licence classifiers are deprecated.versioncan be static, as here, or dynamic: writedynamic = ["version"]and let a plugin likehatch-vcsread it from the Git tag. Dynamic versions mean the tag is the single source of truth, so you never forget to bump the file. Static versions withuv version --bump minorare simpler and also fine.optional-dependenciesvsdependency-groups. Extras are public: they are written into the wheel's metadata and users install them withuv add "slug-kit[cli]". Dependency groups (PEP 735) are private to your repo. When the wheel was built, thedevgroup did not appear in its metadata at all. Put pytest and Ruff in a group, never in an extra.
A wheel is just a zip with a .dist-info folder, and METADATA inside it uses email-header syntax. You can inspect one with nothing but the standard library:
Press Run (⌘ Enter) to see what happens.On a real build, unzip -l dist/*.whl shows the same structure. Checking it before your first release takes ten seconds and catches most packaging mistakes.
Using normalize from the wheel-tags example, what does this print?
print(normalize("My.Cool__Lib"))Data files and the py.typed marker
Libraries often ship non-Python files: templates, a stopword list, a JSON schema. Put them inside the package folder (src/slug_kit/data/stopwords.txt) and the build backend includes them in the wheel. Then read them with importlib.resources, never with a path built from __file__:
from importlib.resources import files
def stopwords() -> set[str]:
text = files("slug_kit").joinpath("data/stopwords.txt").read_text(encoding="utf-8")
return set(text.split())files() works whether the package was installed from a wheel, in editable mode, or loaded from a zip file, where __file__ arithmetic breaks.
If your library has type hints, ship an empty file called py.typed in the package (PEP 561). Without it, mypy and pyright ignore your annotations and treat everything a user imports from you as Any. uv init --lib creates the file for you, and it is one of the cheapest quality signals a library can give.
Test the thing you ship
The src layout from Project Structure exists so your tests import the installed package. During development that install is editable: uv sync (or uv pip install -e .) points the environment at your source folder, so edits take effect without reinstalling.
Editable installs hide one class of bug: a file that exists in your repo but is not in the wheel. So before a release, install the built wheel into a clean environment and smoke-test it:
uv build --no-sourcesuv run --isolated --no-project --with dist/slug_kit-0.1.0-py3-none-any.whl -- python -c "import slug_kit; print(slug_kit.slugify('The Art of Packaging'))"If the data file had been left out, this fails here instead of in a user's production build. Many projects run exactly this step in CI on every pull request.
Publishing with Trusted Publishing
Upload to TestPyPI first. It is a separate index with separate accounts, built for rehearsals: you check the project page renders, the metadata is right, and uv add --index https://test.pypi.org/simple/ slug-kit works.
For real releases, use Trusted Publishing instead of an API token. You tell PyPI "releases for slug-kit come from this GitHub repository, this workflow file, this environment". At release time, GitHub issues the job a signed OIDC identity token, PyPI checks it against that configuration, and hands back an upload token that expires within minutes. There is no long-lived secret to leak, rotate or steal from a fork.
The job can only ask for a token because it was given permissions: id-token: write.
name: release
on:
push:
tags: ["v*"]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4 # check for the current major versions
- uses: astral-sh/setup-uv@v6
- run: uv build --no-sources
- run: uv run --isolated --no-project --with dist/*.whl -- python -c "import slug_kit"
- uses: actions/upload-artifact@v4
with: { name: dist, path: dist/ }
publish:
needs: build
runs-on: ubuntu-latest
environment: pypi # add required reviewers to this environment
permissions:
id-token: write # lets this job request the OIDC token
steps:
- uses: actions/download-artifact@v4
with: { name: dist, path: dist/ }
- uses: pypa/gh-action-pypi-publish@release/v1Building and publishing are separate jobs on purpose: the build job runs your code and third-party tools, while only the publish job holds upload rights. The official pypa/gh-action-pypi-publish action also generates attestations (PEP 740), signed statements that this file came from this workflow, which PyPI shows on the release page. uv publish supports Trusted Publishing too and uploads attestation files it finds next to your distributions. Run uv publish --dry-run locally to see what it would upload. Outside a CI job it reports that no OIDC token was found, which is the point.
Order a careful first release of a new library.
- Tap the steps below in the right order.
After the release: versions, yanking, deprecation
PyPI files are permanent. You can delete a release, but you can never upload a different file with the same name again. Shipped a broken 0.4.0? Fix it and release 0.4.1.
Then yank 0.4.0 (PEP 592). A yanked release is skipped by resolvers unless someone pins it exactly, so new installs avoid it while existing lockfiles that point at it keep working. Deleting would break those lockfiles. Yank, do not delete.
Use semantic versioning as a promise to users: patch for fixes, minor for new features, major for breaking changes. Before 1.0, many projects treat minor bumps as breaking, so say what you do in the README. uv version --bump patch updates the version in pyproject.toml.
Breaking changes deserve a deprecation period. Keep the old function for at least one minor release and make it warn:
from warnings import deprecated # Python 3.13+, or typing_extensions on older versions
@deprecated("make_slug() is deprecated, use slugify()")
def make_slug(title: str) -> str:
return slugify(title)@warnings.deprecated emits a DeprecationWarning at call time and lets type checkers flag every call site. Users who run tests with -W error::DeprecationWarning find the change before it breaks them.
Match each pyproject.toml entry to what it does for users.
- sdist
- A source distribution: your source plus metadata, which must be built on install.
- wheel
- A pre-built zip archive that installers unpack directly, tagged by Python, ABI and platform.
- build backend
- The library named in
[build-system](uv_build, hatchling, setuptools) that creates sdists and wheels. - extra
- An optional set of public dependencies, installed with
package[name]. - dependency group
- A PEP 735 list of dev-only dependencies that is never published.
- Trusted Publishing
- Publishing to PyPI with a short-lived OIDC token from CI instead of a stored API token.
- yank
- Marking a release so resolvers skip it unless it is pinned exactly.