Sub topic 3
Testing and Publishing a Built Python Package
Assume you know virtual environments, pip, Git, and have already built dist/*.whl and dist/*.tar.gz. The safest release process tests these exact files, not an editable checkout.
Test the wheel in a clean environment
Create a temporary environment and install the wheel:
python -m venv /tmp/greeter-verify
/tmp/greeter-verify/bin/python -m pip install dist/greeter-0.1.0-py3-none-any.whl
/tmp/greeter-verify/bin/greeter AdaThe command should print Hello, Ada!. Also run the package’s tests against the installed package. This catches missing package data, incorrect dependencies, and broken console scripts.
/tmp/greeter-verify/bin/python -m pip install ".[test]"
/tmp/greeter-verify/bin/python -m pytestInstalling from the wheel matters because a source checkout can hide packaging mistakes.
Rehearse on TestPyPI
TestPyPI is a separate package index for release practice. Upload the artifacts with twine:
python -m pip install build twine
python -m twine check dist/*
python -m twine upload --repository testpypi dist/*Install from TestPyPI in another clean environment. You may need the normal PyPI index as an additional source for dependencies:
python -m pip install --index-url https://test.pypi.org/simple/ \
--extra-index-url https://pypi.org/simple/ greeter==0.1.0Publish to PyPI
After checking the rehearsal, upload the same artifacts to PyPI:
python -m twine upload dist/*A published version cannot be replaced. Choose and verify the version before uploading.
Automate trusted releases
Trusted publishing uses GitHub’s short-lived OpenID Connect identity instead of a stored PyPI token. Configure PyPI’s trusted publisher for the repository and pypi environment, then grant the workflow permission:
permissions:
id-token: writeA release workflow checks out the tagged commit, installs build, runs python -m build, and uses pypa/gh-action-pypi-publish@release/v1. Trigger it only for published GitHub releases.
Maintain a release
If a release has a serious defect, yank it on PyPI. Yanking discourages new installations while allowing users with an exact version pin to install it. Publish a fixed version instead of deleting history. For breaking changes, deprecate the old API, document the replacement, and record the change in a changelog.
Exercise
Why test a wheel in a fresh environment before uploading it?
Show answer
It verifies that the built artifact contains the package, metadata, dependencies, and entry points that users will actually install.