Chuyển đến nội dung

Bài 18 · Building and Publishing

Publishing to PyPI

Upload your package safely: check distributions, try TestPyPI, use twine or uv publish, set up trusted publishing from GitHub Actions, and follow a release checklist.

Publishing makes your package installable by anyone with pip install your-name. It is quick, but it is also permanent: files you upload cannot be changed or replaced, and names cannot be reused once they are taken. That is why professionals check first, rehearse on a test index and automate releases through CI with short-lived credentials instead of passwords.

None of the upload commands can run in your browser (no network access to the index and no real shell), so they are read-only here. The live examples implement the pre-flight checks that twine check and PyPI itself perform, so you can see what they are looking for.

The pieces

  • PyPI (pypi.org) is the real index. TestPyPI (test.pypi.org) is a separate rehearsal copy where you can practice; it is wiped occasionally and is not mirrored.
  • Accounts need two-factor authentication. Uploads authenticate with an API token (scoped to one project) or, better, Trusted Publishing, where PyPI trusts a specific GitHub Actions workflow and issues a short-lived token on demand: nothing secret to store.
  • Uploaders: twine upload, uv publish, flit publish, hatch publish, poetry publish, or the official pypa/gh-action-pypi-publish action.

Step 1: check the project name

Search pypi.org for your name. Names are normalized (My_Tool equals my-tool), first come first served, and similar names that could confuse users are blocked. Pick a distinctive name; a clash found at upload time costs you a rename.

Python Normalized name clash check

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Step 2: build and check

Terminal
rm -rf dist/
python -m build
python -m pip install twine
twine check dist/*          # validates metadata and README rendering

twine check makes sure that required metadata exists, that the long description is valid for its declared content type (so PyPI will not show a broken page), and that there are no obviously rejected fields. It is fast. Run it in CI on every pull request.

Pre-upload errors are cheap; post-upload errors are permanent. Here is a pre-flight function covering what these checks care about:

Python A pre-flight checker for a built wheel's METADATA

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Step 3: rehearse on TestPyPI

Terminal
twine upload --repository testpypi dist/*
# in a clean environment:
pip install --index-url https://test.pypi.org/simple/ \
            --extra-index-url https://pypi.org/simple/ weather-cli
weather --version

The --extra-index-url is necessary because your dependencies (such as requests) live on the real PyPI, not on TestPyPI. Treat TestPyPI as a place to check how the page renders and that the wheel installs and runs; do not trust packages found there.

Step 4: publish for real

Terminal
twine upload dist/*                 # prompts for __token__ and the token value
# or
uv publish                          # uses UV_PUBLISH_TOKEN or trusted publishing

Tokens: create one at pypi.org → Account settings → API tokens. The username is the literal string __token__, the password is the token. After the first upload, replace it with a token scoped to that single project. Store it in a secrets manager or CI secret, never in the repository. A leaked token lets anyone publish as you.

Trusted publishing from GitHub Actions

Trusted publishing (OIDC) removes long-lived tokens entirely. On PyPI you register the repository, workflow file and (optionally) an environment name as a "trusted publisher". During the workflow run, GitHub proves its identity to PyPI, which returns a token valid for minutes.

YAML
# .github/workflows/release.yml
name: Release
on:
  push:
    tags: ["v*"]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with: { fetch-depth: 0 }          # full history for tag-derived versions
      - 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: actions/upload-artifact@v4
        with: { name: dist, path: dist/ }

  publish:
    needs: build
    runs-on: ubuntu-latest
    environment: pypi                     # protect with required reviewers
    permissions:
      id-token: write                     # needed for trusted publishing
    steps:
      - uses: actions/download-artifact@v4
        with: { name: dist, path: dist/ }
      - uses: pypa/gh-action-pypi-publish@release/v1

Notice that the job that holds id-token: write only downloads and uploads files; the build runs in a separate job. Keeping the privileged step minimal limits the damage if a build dependency is compromised.

flowchart LR
    T["git tag v1.3.0"] --> B["Build job:<br/>wheel + sdist, checks"]
    B --> A["dist/ artifact"]
    A --> P["Publish job<br/>(OIDC, protected environment)"]
    P --> I["PyPI verifies the workflow identity<br/>and accepts the upload"]

No password or token is stored anywhere; PyPI trusts the specific workflow.

After the upload

  • Verify: install the released version in a fresh environment and run a smoke test.
  • Provenance: the publish action can attach signed attestations (PEP 740) so users can verify where files came from.
  • Yank, do not delete: if a release is broken, yank it on the project's page; resolvers skip it, but pinned users are not broken. Then publish a fixed version.
  • Security contacts: add Security under [project.urls] and a SECURITY.md.

Release checklist

  1. Tests, linters and type checks pass on the main branch.
  2. Changelog updated; version chosen and tagged.
  3. Clean build: dist/ empty, python -m build.
  4. twine check dist/*; list wheel and sdist contents.
  5. Install the wheel in a fresh environment; run a smoke test from another directory.
  6. Upload to TestPyPI (first release, or when changing metadata or README).
  7. Publish through CI with trusted publishing.
  8. Verify install from PyPI; announce; start the next Unreleased section.
Python The checklist as a tiny release gate

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Why use Trusted Publishing instead of a stored API token?

    OIDC trust means GitHub proves the workflow's identity, and PyPI mints a token valid only for the upload.
  2. 2. You uploaded a release with a serious bug. What should you do?

    Filenames cannot be reused. Yanking keeps exact pins working while resolvers skip it.
  3. 3. Why does installing from TestPyPI use --extra-index-url https://pypi.org/simple/?

    TestPyPI only has what you or others uploaded there; dependencies come from the real index.
  4. 4. What does twine check dist/* verify?

    It validates metadata and README rendering before you upload.

Summary

  • Publishing is permanent: files and names cannot be reused, so check first.
  • Build clean, run twine check, list contents, test in a fresh environment, rehearse on TestPyPI.
  • Upload with twine upload or uv publish; prefer Trusted Publishing from CI over API tokens.
  • Separate the build job from the privileged publish job and protect it with an environment.
  • Yank bad releases and publish a new version.
  • Follow a release checklist and automate it.

Next: Version Specifiers and PEP 440

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.