Monday, June 08, 2026

Build, Test, and Publish a Python Package to PyPI

Before you push a release to the Python Package Index, it pays to build and test it locally so you catch problems before your users do. This guide walks through the full workflow: setting up an isolated environment, installing your package in editable mode, running the test suite, building the distribution, validating the metadata, uploading with Twine, and tagging the release in Git. (If you are starting from scratch and need to structure the package itself first, see How To Create A Python Package.)

Build, Test & Publish a PyPI Packagevenvcreate +activateInstalldeps +pip -e .Testpytest -vBuildpython-m buildChecktwinecheckUploadtwineuploadTaggit tag+ pushTest locally and validate metadata before you ever upload to PyPI.

1. Set up an isolated environment

Install the Python version you need. If your package depends on TensorFlow, use Python 3.11, since the newest releases are not always supported right away. On macOS with Homebrew:

brew install python@3.11

Verify the version:

python3.11 --version

Create a virtual environment so you do not disturb the Homebrew-managed system packages, then activate it:

python3.11 -m venv venv
source venv/bin/activate

2. Install dependencies and your package

List your dependencies in a requirements.txt file and install them:

pip install -r requirements.txt

Install your own package in editable mode so code changes are picked up without reinstalling:

pip install -e .

3. Run the tests

Run the test suite and make sure everything passes before going any further:

pytest -v

4. Build the distribution

Update the version and metadata in pyproject.toml, then remove any stale build artifacts so you get a clean build:

rm -rf dist/ build/ *.egg-info

Generate the fresh source distribution and wheel:

python3 -m build

5. Validate the metadata

Check the built artifacts for metadata problems before uploading, so you do not waste a version number on a broken release:

twine check dist/*

6. Publish to PyPI

Upload the validated distribution. Twine will prompt for your PyPI credentials or API token:

twine upload dist/*

7. Tag the release in Git

Finally, tag the release in your repository and push the tag so the published version is traceable to a commit:

git tag -a v3.0.0 -m "Release version 3.0.0"
git push origin v3.0.0

Summary

The discipline that keeps PyPI releases clean is simple: work inside a virtual environment, install editable, run pytest, build from a cleaned directory, run twine check before twine upload, and tag every release in Git. Following this order means each version you publish has been tested and validated first.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.