Structure Your Package With pyproject.toml
Modern Python packaging centers on pyproject.toml. As documented in the Python Packaging Authority's guide to writing pyproject.toml, new projects should declare metadata in the standardized [project] table (PEP 621) alongside [build-system]. Legacy setup.py scripts are only needed for custom build hooks like compiling C extensions, and Poetry 2.0 (released January 5, 2025) also supports [project].
Organize your repository with the src/ layout from PyPA's Packaging Python Projects tutorial:
- Repository root: keep
pyproject.toml,README.md,LICENSE, andtests/at the top level. - Source folder: put your importable code under
src/your_package_name/with an__init__.pyfile so tests run against the installed distribution rather than the raw checkout. - Naming rules: distribution names allow ASCII letters, digits, underscores, hyphens, and periods, and cannot begin or end with punctuation. PyPI compares names case-insensitively and treats runs of
-,_, and.as equivalent.
Verify availability against PyPI's naming rules. Even an unused search result can be unavailable if it conflicts with a Python Standard Library module, triggers typosquatting similarity checks, sits on PyPI's prohibited list (like requirements.txt), or was registered without a release.
Under [build-system], pick a backend that supports PEP 621 and PEP 639 license expressions (license = "MIT" and license-files = ["LICEN[CS]E*"]). PyPA's tutorial uses Hatchling (hatchling >= 1.26), while Setuptools (setuptools >= 77.0.3), Flit (flit_core >= 3.12.0, <5), PDM (pdm-backend >= 2.4.0), and uv_build (uv_build >= 0.13, <0.14) read the same [project] metadata. Keep one distinction clear: classifiers only power PyPI search filters, whereas requires-python is enforced by installers like pip. For internal packages that must never leak to public PyPI, add the Private :: Do Not Upload classifier.
Build Source Distributions and Wheels
Per PyPA's package formats guide, every PyPI release should ship both a source distribution (sdist) and at least one built distribution (wheel).
| Format | Filename pattern | Contents | Role |
|---|---|---|---|
| sdist | name-version.tar.gz | Raw source tree, PKG-INFO metadata, and often tests or docs | Installer fallback and upstream input for Linux distros, Conda, and Homebrew |
| Wheel | name-version-py3-none-any.whl or platform-tagged .whl | ZIP archive of installable files, METADATA, and RECORD hashes (no .pyc, tests, or docs) | Installs directly without running a build backend; required for fast installs and compiled extensions |
Even pure-Python libraries need a universal py3-none-any.whl because pip cannot install an sdist directly without spinning up a build environment first. Build both archives locally using either standard tool:
- PyPA build: install
build(python3 -m pip install --upgrade build, orpy -m buildon Windows) and runpython3 -m buildfrom your project root to output both files indist/. - uv build: following the uv package publishing guide, run
uv build --no-sourcesso localtool.uv.sourcesoverrides are disabled and your build stays compatible with standard frontends.
Unpack the wheel as a ZIP archive to verify no stray fixtures or secrets slipped in, then run twine check dist/*. As noted in PyPI's publishing troubleshooting docs, uploads fail if your long description does not render. Check sizes against PyPI storage limits: defaults are 100.0 MB per file and 10.0 GB per project (organization-owned projects get 200.0 MB per file and 20.0 GB total).
Set Up 2FA and Rehearse on TestPyPI
PyPI has required two-factor authentication (2FA) on every account since 2024, and plain username-and-password uploads are no longer accepted. After verifying your email on pypi.org, complete 2FA setup in two steps:
- Generate and verify recovery codes: PyPI requires you to generate single-use recovery codes, store them safely, and submit ("burn") one code before enabling any 2FA method.
- Add a phishing-resistant key: PyPI prefers a FIDO-compliant WebAuthn security device (such as a USB key or passkey) over TOTP apps because WebAuthn validates the domain automatically. Adding two methods prevents accidental lockout.
Rehearse every first release on TestPyPI (https://test.pypi.org/), a separate index with its own user database that is periodically pruned. Upload your dist/* files with Twine (python3 -m twine upload --repository testpypi dist/*) or via a TestPyPI Trusted Publisher, check how the project page renders, and test installing the wheel inside a clean virtual environment:
python3 -m pip install --index-url https://test.pypi.org/simple/ --no-deps --only-binary=:all: your-package
Follow PyPA's warning closely: never mix TestPyPI and PyPI using --extra-index-url, because pip does not prioritize PyPI and could install an unintended or malicious dependency from TestPyPI. Install runtime dependencies from PyPI first, then install your wheel from TestPyPI with --no-deps. With uv, you can also verify an isolated import using uv run --with your-package --no-project -- python -c "import your_package".
Publish With OIDC Trusted Publishers and Immutable Versions
Storing long-lived PyPI API tokens in CI secrets is obsolete. PyPI's Trusted Publishing uses OpenID Connect (OIDC) to mint short-lived tokens directly between your CI runner and PyPI across GitHub Actions, GitLab CI/CD (gitlab.com), Google Cloud, and ActiveState.
You can publish a brand-new package without a manual initial upload by creating a pending Trusted Publisher under your PyPI account settings. Enter the intended project name, GitHub owner, repository, workflow filename (such as publish.yml), and GitHub Environment (such as pypi). On the first release run, PyPI creates the project and promotes the pending publisher to an active one. Note that a pending publisher does not reserve the package name until your first upload runs.
Follow the PyPA GitHub Actions publishing guide and PyPI's publisher usage guide:
- Scope OIDC to the publish job: set
permissions: id-token: writeat the job level (never workflow-wide). - Gate the release environment: attach a
pypiGitHub Environment with required manual approvals so tags or PRs cannot ship unreviewed releases. Mirror the setup on TestPyPI with atestpypienvironment. - Use the official action or uv: call
pypa/gh-action-pypi-publish@release/v1(withrepository-url: https://test.pypi.org/legacy/for TestPyPI) or runuv publish, which handles Trusted Publishing automatically and attempts to invalidate the short-lived token afterward. - Include PEP 740 attestations: GitHub Actions, GitLab CI/CD, and Google Cloud Trusted Publishers support PyPI digital attestations (in-toto
PyPI PublishandSLSA Provenance), cryptographically proving where each file was built.
Treat every published version tag as immutable. Per PyPI's filename rules, a filename (project-version-type) can never be reused, even after deleting the file or recreating the project. Always bump the version (for example 0.1.1), rebuild, and re-upload. Note also PyPI's version length limit: since October 23, 2026, normalized versions exceeding 128 characters are rejected.
If a release is broken or vulnerable, do not delete it and break pinned downstream builds. Instead, use PyPI yanking (PEP 592) with a clear reason so installers skip the release unless explicitly pinned with == or === (yanking applies to entire releases and does not free storage).
Optimize Your PyPI Page and Reach Python Developers
Before announcing, tighten the fields covered in PyPI's project descriptions guide and project metadata docs:
- Lead with a runnable README: open with a one-sentence value proposition, a copyable
pip installoruv addcommand, a short working code snippet, and full HTTPS URLs for any images. - Use PEP 753 well-known URL labels: define
Homepage,Documentation,Repository,Issues, andChangelogunder[project.urls]per the well-known project URLs spec. Repository URLs matching your GitHub Actions or GitLab Trusted Publisher display a Verified badge on PyPI. - Publish a clean changelog: follow our changelog writing guide so developers can inspect breaking changes and release cadence immediately.
PyPI has no discovery feed for new libraries, so coordinate external distribution with our launch checklist and open-source launch guide:
- Share code-first launch posts: post a concise example on r/Python or domain subreddits (see our Reddit launch guide), write a grounded Show HN post covering architecture trade-offs, and submit stable releases to Python weekly newsletters.
- List on developer boards: submit your docs site or repo to developer directories like DevHunt.
- List on Hauntboard: you can submit your Python package on Hauntboard free (reviewed by a person in about 72 hours, with 20 free places a week and a dofollow link while the badge is up) or choose Launch Now ($19, reviewed within 24 hours) for 7 days at the top of New this week with public page views, visits sent, and votes.
- Track docs clicks: tag your launch links and follow how to track launch traffic to see which communities bring real GitHub issues and adopters.
Frequently Asked Questions
Do I need a setup.py file to publish on PyPI in 2026?
No. For pure-Python projects, pyproject.toml with [build-system] and [project] replaces setup.py across Hatchling, Setuptools, Flit, PDM, Poetry 2.0+, and uv_build. Keep setup.py only for programmatic build logic such as custom native extensions.
Can I re-upload a fixed distribution under the same version on PyPI?
No. PyPI permanently forbids filename reuse, even after deleting a release or project. Bump the version number, rebuild your sdist and wheel, upload the new release, and yank the broken version if users should avoid it.
Why use Trusted Publishing instead of a PyPI API token?
Trusted Publishing exchanges short-lived OIDC tokens directly from GitHub Actions, GitLab CI/CD, Google Cloud, or ActiveState, removing static CI secrets that can leak while enabling verified repository links and PEP 740 publish attestations.
Can I publish a private Python package to PyPI?
No. PyPI only hosts public packages. For private internal libraries, run a private index like devpi (as PyPI's documentation recommends) and include the Private :: Do Not Upload classifier in pyproject.toml to block accidental public uploads.