pyproject.toml is the single configuration file for a modern Python package: it tells installers how to build your project, holds the metadata PyPI shows, lists dependencies and configures tools such as pytest and Ruff. A new project in 2026 needs no setup.py, no setup.cfg and no requirements-dev.txt. This guide builds a small command-line package from scratch, explains each table and field, compares the common build backends, covers the newer standards for license expressions and dependency groups, and ends with an automated release to PyPI without any stored API token.

pyproject.toml packaging workflow: choose a build backend, fill the project table, add dependency groups and entry points, build a wheel and publish to PyPI with trusted publishing
A pyproject.toml packaging flow: build backend, project metadata, dependencies, a built wheel and trusted publishing to PyPI.

From my own work: When I take over internal Python tools, the packaging is often a setup.py copied from an old project, a requirements.txt that does not match it and a license classifier nobody checked. Moving to one pyproject.toml with a src layout usually exposes a missing dependency on the first clean install, which is exactly the point.

Project layout: use the src layout

Put the importable package inside a src directory. Tests then import the installed package rather than the folder next to them, so a file you forgot to include in the wheel fails in CI instead of on a user’s machine:

linkcheck/
├── pyproject.toml
├── README.md
├── LICENSE
├── src/
│   └── linkcheck/
│       ├── __init__.py
│       ├── __main__.py
│       └── cli.py
└── tests/
    └── test_cli.py

With uv installed, uv init --package linkcheck creates this structure and a starter pyproject.toml. Without it, create the folders by hand; nothing below depends on uv.

The [build-system] table and choosing a build backend

The [build-system] table tells pip, uv or python -m build which package builds your project. The frontend installs the listed requirements into an isolated environment and calls the backend (Packaging guide: writing pyproject.toml). The backend only matters at build time; users installing your wheel never see it.

Backend [build-system] configuration Good fit
hatchling requires = ["hatchling>=1.27"], build-backend = "hatchling.build" Pure Python packages, plugins such as hatch-vcs for Git versions
uv_build requires = ["uv_build>=0.13.10,<0.14"], build-backend = "uv_build" Pure Python projects managed with uv; very fast, deliberately few options
setuptools requires = ["setuptools>=77"], build-backend = "setuptools.build_meta" Existing projects, C extensions, complex package data
scikit-build-core, maturin, meson-python Backend-specific Compiled code in C, C++ or Rust

The minimum versions matter: hatchling 1.27 and setuptools 77 are the first releases that write the SPDX license fields described below. uv recommends an upper bound on uv_build because its minor versions may change behaviour (uv: build backend).

A complete pyproject.toml example

Here is a full file for the example package, using hatchling:

[build-system]
requires = ["hatchling>=1.27"]
build-backend = "hatchling.build"

[project]
name = "linkcheck-cli"
version = "0.3.0"
description = "Check a sitemap for broken links and redirect chains."
readme = "README.md"
requires-python = ">=3.10"
license = "MIT"
license-files = ["LICENSE"]
authors = [{ name = "Your Name", email = "you@example.com" }]
keywords = ["seo", "sitemap", "broken links"]
classifiers = [
    "Development Status :: 4 - Beta",
    "Environment :: Console",
    "Programming Language :: Python :: 3",
    "Programming Language :: Python :: 3.10",
    "Programming Language :: Python :: 3.14",
    "Topic :: Internet :: WWW/HTTP :: Site Management :: Link Checking",
]
dependencies = [
    "httpx>=0.28",
    "rich>=13.7",
]

[project.optional-dependencies]
xlsx = ["openpyxl>=3.1"]

[project.scripts]
linkcheck = "linkcheck.cli:main"

[project.urls]
Homepage = "https://github.com/example/linkcheck-cli"
Issues = "https://github.com/example/linkcheck-cli/issues"
Changelog = "https://github.com/example/linkcheck-cli/blob/main/CHANGELOG.md"

[dependency-groups]
test = ["pytest>=8.3", "pytest-cov>=6"]
lint = ["ruff>=0.14"]
dev = [{ include-group = "test" }, { include-group = "lint" }]

[tool.hatch.build.targets.wheel]
packages = ["src/linkcheck"]

[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-ra"

[tool.ruff]
line-length = 100
target-version = "py310"

[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B"]

The field reference lives in the PyPA specification (PyPA: pyproject.toml specification). The fields that cause most mistakes:

  • name is the distribution name on PyPI (linkcheck-cli); it may differ from the import name (linkcheck). Check that the name is free on PyPI before you start.
  • requires-python stops pip from installing your package on interpreters you do not test. Python 3.9 reached end of life in October 2025, so >=3.10 is a sensible floor today.
  • dependencies are lower bounds for libraries. Avoid exact pins such as httpx==0.28.1 in a library; they conflict with other packages in the user's environment. Pin exact versions in your application lock file instead.
  • classifiers are optional labels for search on PyPI. Do not add License :: classifiers when you use a license expression.

SPDX license expressions (PEP 639)

The older form license = { text = "MIT" } or license = { file = "LICENSE" } is deprecated. Under PEP 639, license is a plain SPDX expression string and license-files lists glob patterns for the files to ship in the wheel (PEP 639):

license = "MIT"                              # single license
license = "Apache-2.0 OR MIT"                # dual licensed
license = "GPL-3.0-or-later"                 # use the exact SPDX identifier
license-files = ["LICEN[CS]E*", "NOTICE"]    # globs relative to pyproject.toml

Build tools validate the expression, and PyPI shows it in a structured field. Mixing the new string with a License :: classifier makes current backends refuse to build.

Optional dependencies vs dependency groups

These look similar but serve different people. [project.optional-dependencies] (extras) are published with the package; users install them with pip install "linkcheck-cli[xlsx]". [dependency-groups], standardised in PEP 735, are for the project's own developers: test runners, linters, docs tools. They are not part of the published metadata, and groups can include each other (PyPA: dependency groups).

# uv: groups are installed into the project environment
uv sync --group dev
uv run pytest

# pip 25.1 or newer can install groups directly
python -m pip install --group dev
python -m pip install -e .

This replaces the old pattern of a requirements-dev.txt next to a dev extra that leaked test tools to every user who asked for it.

Command-line entry points

[project.scripts] maps a command name to a function. The installer creates the linkcheck executable, including a .exe wrapper on Windows, so users never type python -m:

# src/linkcheck/cli.py
import argparse
import sys

import httpx


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(prog="linkcheck", description="Check URLs for errors.")
    parser.add_argument("urls", nargs="+")
    args = parser.parse_args(argv)
    failed = 0
    with httpx.Client(follow_redirects=False, timeout=15) as client:
        for url in args.urls:
            status = client.head(url).status_code
            print(f"{status} {url}")
            failed += status >= 400
    return 1 if failed else 0


if __name__ == "__main__":
    sys.exit(main())
# src/linkcheck/__main__.py  (enables: python -m linkcheck)
from linkcheck.cli import main

raise SystemExit(main())

Return an integer exit code from main; the generated wrapper passes it to sys.exit, which makes the tool usable in shell scripts and CI.

Version from Git tags

Hard-coding the version works, but it is easy to tag v0.4.0 and forget to edit the file. With hatchling, the hatch-vcs plugin reads the version from the latest Git tag at build time:

[build-system]
requires = ["hatchling>=1.27", "hatch-vcs>=0.4"]
build-backend = "hatchling.build"

[project]
name = "linkcheck-cli"
dynamic = ["version"]        # remove the static version line

[tool.hatch.version]
source = "vcs"

[tool.hatch.build.hooks.vcs]
version-file = "src/linkcheck/_version.py

Add the generated _version.py to .gitignore. In CI, check out with full history (fetch-depth: 0) so the tag is visible.

Build, inspect and test the package

# build an sdist and a wheel into dist/
uv build                       # or: python -m pip install build && python -m build

# check metadata and README rendering
uvx twine check dist/*         # or: python -m pip install twine && twine check dist/*

# list what actually went into the wheel
python -m zipfile -l dist/linkcheck_cli-0.3.0-py3-none-any.whl

# install the wheel into a fresh environment and run it
python -m venv /tmp/lc && /tmp/lc/bin/pip install dist/*.whl
/tmp/lc/bin/linkcheck https://example.com/

The install test is the one people skip, and it is the one that catches a missing dependency or a module left out of the wheel. Upload to TestPyPI first for the very first release: uv publish --publish-url https://test.pypi.org/legacy/, then install from there with --index-url https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple/.

Publish to PyPI with trusted publishing

Trusted publishing replaces long-lived PyPI API tokens with OpenID Connect: you register your GitHub repository, workflow file and environment as a trusted publisher in the project settings on PyPI, and the workflow receives a short-lived upload token at run time (PyPI: trusted publishers). The official workflow from the Packaging User Guide splits build and upload into separate jobs so only the upload job can mint a token (Packaging guide: publishing with GitHub Actions):

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

permissions: {}

jobs:
  build:
    runs-on: ubuntu-24.04
    permissions:
      contents: read
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0
          persist-credentials: false
      - uses: actions/setup-python@v6
        with:
          python-version: "3.14"
      - run: python -m pip install build twine
      - run: python -m build
      - run: twine check --strict dist/*
      - uses: actions/upload-artifact@v5
        with:
          name: dist
          path: dist/

  publish:
    needs: build
    runs-on: ubuntu-24.04
    environment:
      name: pypi
      url: https://pypi.org/project/linkcheck-cli/
    permissions:
      id-token: write          # required for trusted publishing
    steps:
      - uses: actions/download-artifact@v5
        with:
          name: dist
          path: dist/
      - uses: pypa/gh-action-pypi-publish@release/v1

Add required reviewers to the pypi environment and pin the actions to commit SHAs, as described in GitHub Actions security hardening. If some other tool still needs a token, keep it out of the repository using the rules in .env file and secrets best practices.

Run the test suite on every pull request before tags are ever pushed; if tests are unreliable, the method in finding flaky tests from JUnit XML helps you fix them before they block releases.

Migrating from setup.py

  • Move name, version, install_requires (to dependencies), extras_require (to optional-dependencies) and entry_points["console_scripts"] (to [project.scripts]) into pyproject.toml.
  • Keep setuptools as the backend at first; switching backends and metadata in one step makes failures harder to locate.
  • Compare old and new wheels with python -m zipfile -l and the METADATA file inside them.
  • Delete setup.py once no custom build logic remains; a three-line stub is only needed for very old tooling.

pyproject.toml checklist

  • src layout, distribution name checked on PyPI.
  • [build-system] with a current minimum version of the backend.
  • requires-python, lower-bound dependencies, extras only for user-facing features.
  • SPDX license string and license-files, no license classifiers.
  • Development tools in [dependency-groups].
  • Console script entry point that returns an exit code.
  • Wheel contents listed and install-tested in a clean environment.
  • Trusted publishing from a tag-triggered workflow with a protected environment.

Want this done on your own server or site?

I am Saizul Amin, a web developer and technical SEO consultant. I set up and harden VPS servers, migrate WordPress sites, fix indexing problems and build automations. See my portfolio or get in touch.

FAQ

Do I still need setup.py with pyproject.toml?

No, not for a new project. All metadata and dependencies go into the [project] table, and the build backend is declared in [build-system]. Keep setup.py only if you have custom build logic that your backend cannot express in configuration.

Which build backend should I use in pyproject.toml?

For pure Python packages, hatchling or uv_build are simple and fast; setuptools is the safe choice for existing projects and C extensions. For Rust or C++ extensions, use maturin or scikit-build-core.

What is the difference between optional-dependencies and dependency-groups?

Optional dependencies, also called extras, are published with your package so users can install features such as pkg[xlsx]. Dependency groups are for project development only, such as test and lint tools, and are not included in the published package metadata.

How do I write the license field in pyproject.toml now?

Use an SPDX expression string such as license = "MIT" or "Apache-2.0 OR MIT", and list license files with license-files. The older table forms are deprecated, and License classifiers should not be combined with the new string.

How do I publish to PyPI without an API token?

Configure a trusted publisher on PyPI for your GitHub repository and workflow, give the upload job id-token: write permission, and use pypa/gh-action-pypi-publish. PyPI then issues a short-lived token for each run.

Sources

NEW BLOGS. REAL STRATEGIES. REAL RESULTS.

Join our community and receive powerful SEO tips, web optimization guides, and growth strategies as soon as they’re published.

Don’t just read blogs — stay ahead of the competition.

We don’t spam! Read our privacy policy for more info.

Share.

Comments are closed.