search
HomeBackend DevelopmentPython TutorialTrusted publishing ‐ It has never been easier to publish your python packages

Publishing Python packages used to be a daunting task, but not any more. Even better, it has become significantly more secure. Gone are the days of juggling usernames, passwords, or API tokens while relying on CLI tools. With trusted publishing, you simply provide PyPI with the details of your GitHub repository, and GitHub Actions takes care of the heavy lifting.

How to Publish Your Python Package with Trusted Publishing

I will introduce a workflow that will publish your package to TestPyPi when a tag is created (on the development branch), or to PyPi when you merge to the main branch.

Prepare Your Package for Publishing

Ensure your Python package follows PyPI’s packaging guidelines. At a minimum, you’ll need:

  • A setup.py or pyproject.toml file defining your package metadata.
  • Properly structured code with a clear directory layout.
  • A README file to showcase your project on PyPI.

For a detailed checklist, refer to the Python Packaging User Guide.

Configure GitHub Actions in Your Repository

Let's start by creating a new GitHub action .github/workflows/test-build-publish.yml.

name: test-build-publish

on: [push, pull_request]

permissions:
  contents: read

jobs:

  build-and-check-package:
    name: Build & inspect our package.
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4
      - uses: hynek/build-and-inspect-python-package@v2

This action will build your package and uploads the built wheel and the source distribution (SDist) as GitHub Actions artefacts.

Next, we add a step to publish to TestPyPI. This step will run whenever a tag is created, ensuring that the build from the previous step has completed successfully. Replace PROJECT_OWNER and PROJECT_NAME with the appropriate values for your repository.

  test-publish:
    if: >-
        github.event_name == 'push' &&
        github.repository == 'PROJECT_OWNER/PROJECT_NAME' &&
        startsWith(github.ref, 'refs/tags')
    needs: build-and-check-package
    name: Test publish on TestPyPI
    runs-on: ubuntu-latest
    environment: test-release
    permissions:
      id-token: write
    steps:
      - name: Download packages built by build-and-check-package
        uses: actions/download-artifact@v4
        with:
          name: Packages
          path: dist

      - name: Upload package to Test PyPI
        uses: pypa/gh-action-pypi-publish@release/v1
        with:
          repository-url: https://test.pypi.org/legacy/

This step downloads the artefacts created during the build process and uploads them to TestPyPI for testing.

In the last step, we will upload the package to PyPI when a pull request is merged into the main branch.

  publish:
    if: >-
      github.event_name == 'push' &&
      github.repository == 'PROJECT_OWNER/PROJECT_NAME' &&
      github.ref == 'refs/heads/main'
    needs: build-and-check-package
    name: Publish to PyPI
    runs-on: ubuntu-latest
    environment: release
    permissions:
      id-token: write
    steps:
      - name: Download packages built by build-and-check-package
        uses: actions/download-artifact@v4
        with:
          name: Packages
          path: dist

      - name: Publish distribution ? to PyPI for push to main
        uses: pypa/gh-action-pypi-publish@release/v1

Configure GitHub Environments

To ensure that only specific tags trigger the publishing workflow and maintain control over your release process.
Create a new environment test-release by navigating to Settings -> Environments in your GitHub repository.

Set up the environment and add a deployment tag rule.

Trusted publishing ‐ It has never been easier to publish your python packages

Trusted publishing ‐ It has never been easier to publish your python packages

Limit which branches and tags can deploy to this environment based on rules or naming patterns.

Trusted publishing ‐ It has never been easier to publish your python packages

Limit which branches and tags can deploy to this environment based on naming patterns.

Trusted publishing ‐ It has never been easier to publish your python packages

Configure the target tags.

Trusted publishing ‐ It has never been easier to publish your python packages

The pattern [0-9]*.[0-9]*.[0-9]* matches semantic versioning tags such as 1.2.3, 0.1.0, or 2.5.1b3, but it excludes arbitrary tags like bugfix-567 or feature-update.

Repeat this for the release environment to protect the main branch in the same way, but this time targeting the main branch.

Trusted publishing ‐ It has never been easier to publish your python packages

Set Up a PyPI Project and Link Your GitHub Repository

Create an account on TestPyPI if you don’t have one.
Navigate to your account, Publishing and add a new pending publisher.
Link your GitHub repository to the PyPI project by providing its name, your GitHub username, the repository name, the workflow name (test-build-publish.yml) and the environment name (test-release).

Trusted publishing ‐ It has never been easier to publish your python packages

Repeat the above on PyPI with the environment name set to release.

Test the Workflow

Now whenever you create a tag on your development branch, it will trigger a release to be uploaded to TestPyPI and merging the development branch into main will upload a release to PyPI.

What Wasn't Covered

While this guide provides an introduction to trusted publishing workflows, there are additional steps and best practices you might consider implementing. For example, setting up branch protection rules can ensure only authorized collaborators can push tags or merge to protected branches, like main or develop. You can also enforce status checks or require pull request reviews before merging, adding another layer of quality assurance.

Have a look at my python-repository-template that covers additional enhancement to this workflow, such as requiring unit and static tests to pass, checking the package with pyroma and ensuring that your tag matches the version of your package with vercheck.

Summary

If you've been holding back on sharing your work, now is the perfect time to try trusted publishing.

  • Introducing 'Trusted Publishers' The Python Package Index Blog highlights a more secure publishing method that does not require long-lived passwords or API tokens to be shared with external systems
  • Publishing to PyPI with a Trusted Publisher The official PyPI documentation to get started with using trusted publishers on PyPI.
  • Building and testing Python in the official GitHub docs.

The above is the detailed content of Trusted publishing ‐ It has never been easier to publish your python packages. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does the choice between lists and arrays impact the overall performance of a Python application dealing with large datasets?How does the choice between lists and arrays impact the overall performance of a Python application dealing with large datasets?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

Explain how memory is allocated for lists versus arrays in Python.Explain how memory is allocated for lists versus arrays in Python.May 03, 2025 am 12:10 AM

InPython,listsusedynamicmemoryallocationwithover-allocation,whileNumPyarraysallocatefixedmemory.1)Listsallocatemorememorythanneededinitially,resizingwhennecessary.2)NumPyarraysallocateexactmemoryforelements,offeringpredictableusagebutlessflexibility.

How do you specify the data type of elements in a Python array?How do you specify the data type of elements in a Python array?May 03, 2025 am 12:06 AM

InPython, YouCansSpectHedatatYPeyFeLeMeReModelerErnSpAnT.1) UsenPyNeRnRump.1) UsenPyNeRp.DLOATP.PLOATM64, Formor PrecisconTrolatatypes.

What is NumPy, and why is it important for numerical computing in Python?What is NumPy, and why is it important for numerical computing in Python?May 03, 2025 am 12:03 AM

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

Discuss the concept of 'contiguous memory allocation' and its importance for arrays.Discuss the concept of 'contiguous memory allocation' and its importance for arrays.May 03, 2025 am 12:01 AM

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

How do you slice a Python list?How do you slice a Python list?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

What are some common operations that can be performed on NumPy arrays?What are some common operations that can be performed on NumPy arrays?May 02, 2025 am 12:09 AM

NumPyallowsforvariousoperationsonarrays:1)Basicarithmeticlikeaddition,subtraction,multiplication,anddivision;2)Advancedoperationssuchasmatrixmultiplication;3)Element-wiseoperationswithoutexplicitloops;4)Arrayindexingandslicingfordatamanipulation;5)Ag

How are arrays used in data analysis with Python?How are arrays used in data analysis with Python?May 02, 2025 am 12:09 AM

ArraysinPython,particularlythroughNumPyandPandas,areessentialfordataanalysis,offeringspeedandefficiency.1)NumPyarraysenableefficienthandlingoflargedatasetsandcomplexoperationslikemovingaverages.2)PandasextendsNumPy'scapabilitieswithDataFramesforstruc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor