Lesson 7 of 9 · 24m
Publishing to PyPI Safely
Build, inspect, test on TestPyPI, then publish with trusted publishing and release automation that doesn't depend on a maintainer's laptop.
Publishing should be boring. If releasing requires a maintainer remembering twelve commands on a laptop with the right credentials, you don't have a release process — you have a single point of failure wearing a calendar reminder.
The manual path, so you understand it
rm -rf dist/
python -m build
twine check dist/*
twine upload --repository testpypi dist/*
python -m venv /tmp/pypitest
/tmp/pypitest/bin/pip install --index-url https://test.pypi.org/simple/ acme-metrics==1.4.2
twine upload dist/*TestPyPI is a separate service with separate accounts and packages. It is useful for validating metadata and upload mechanics, but it does not prove installation in a realistic dependency environment because many dependencies are absent or stale there.
Trusted publishing is the modern default
PyPI supports OpenID Connect trusted publishing. Instead of storing a long-lived PyPI API token in CI, GitHub Actions receives a short-lived identity token and exchanges it for upload permission.
permissions:
id-token: write
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: python -m pip install build twine
- run: python -m build
- run: twine check dist/*
- uses: pypa/gh-action-pypi-publish@release/v1This removes the most dangerous secret in the pipeline. Configure the trusted publisher on PyPI with the exact repository, workflow, and environment. Least privilege applies to package indexes too.
Tag, changelog, artifact: one atomic story
A release should connect four things:
git tag v1.4.2
version metadata 1.4.2
GitHub release notes
PyPI artifacts built from that tagAutomate the version check. If the tag says v1.4.2 and pyproject.toml says 1.4.1, fail before upload. PyPI filenames are immutable; you cannot replace mylib-1.4.2-py3-none-any.whl with fixed contents. You can only yank and publish a new version.
Signatures and provenance are increasingly expected
PyPI now emphasizes trusted publishing and attestations rather than manual GPG workflows. Generate attestations where supported, keep provenance in CI, and make releases reproducible enough that users can trace artifact → commit → workflow run.
Field notes
- Upload artifacts once from CI; rebuilding locally and uploading separately creates provenance ambiguity.
- Protect release branches and tags so one compromised maintainer account cannot push arbitrary release code.
- Use a dedicated GitHub environment with required reviewers for high-impact packages.
- A failed upload can be partially visible; check PyPI before retrying blindly.
Was this lesson helpful?