Sub topic 14
Publishing to PyPI
This chapter assumes you can build a greeter project into dist/ with python -m build, and that you have installed the wheel in a clean virtual environment and checked it. It covers the upload step: accounts, tokens, twine, and what to do when an upload fails.
What publishing does
Publishing sends the files in dist/ (the sdist and the wheel) to the Python Package Index (PyPI). PyPI stores them and shows the project page. After that, pip install greeter can find them.
Three properties of PyPI shape everything below:
- Uploads are permanent. You can delete a release, but you can never upload a file with the same name again. If
greeter-0.1.0-py3-none-any.whlhas been uploaded once, that filename is used forever. - Names are global. Only one project can be called
greeter. If the name is taken, the upload is refused. - Metadata comes from the files. PyPI reads the name, version, description, and classifiers out of the artifacts. It does not read your repository.
Because of the first property, you rehearse on TestPyPI first and check the artifacts before any real upload.
Before you upload
Work through this checklist from the project root.
- Confirm the name is free. Open
https://pypi.org/project/greeter/. A 404 means the name is probably available. A project with a similar name may still block yours, because PyPI rejects names that normalize to an existing one (case, dots, dashes, and underscores are treated as equal). - Confirm the version is new. The version in
pyproject.tomlmust not match anything already uploaded. - Remove stale files. Delete
dist/and rebuild so old versions are not uploaded by accident. - Build and validate.
rm -rf dist/
python -m pip install build twine
python -m build
python -m twine check dist/*twine check confirms that the long description renders on PyPI. It prints PASSED for each file. A failure usually means the README has invalid markup or the metadata is malformed.
Create an account and a token
Register on https://pypi.org/account/register/, verify your email, and turn on two-factor authentication. PyPI requires two-factor authentication for publishing.
You also need an API token. Passwords are not accepted for uploads.
- Open Account settings and choose Add API token.
- For a new project, the only scope available is "Entire account".
- After the first upload, create a new token scoped to the
greeterproject and delete the account-wide token. - Copy the token immediately. PyPI shows it once.
Tokens start with pypi-. Treat one like a password. Never commit it to Git.
TestPyPI is a separate service at https://test.pypi.org. It has its own accounts and its own tokens, so a PyPI token does not work there.
Rehearse on TestPyPI
TestPyPI accepts the same uploads as PyPI but is a sandbox. Its data may be wiped, and nobody depends on it.
python -m twine upload --repository testpypi dist/*twine asks for credentials. Enter __token__ as the username and the token as the password. The username is literally the string __token__.
To avoid typing them, put the credentials in ~/.pypirc:
[distutils]
index-servers =
pypi
testpypi
[pypi]
username = __token__
password = pypi-REPLACE_WITH_YOUR_TOKEN
[testpypi]
username = __token__
password = pypi-REPLACE_WITH_YOUR_TEST_TOKENRestrict the file with chmod 600 ~/.pypirc. Alternatively, set the environment variables TWINE_USERNAME and TWINE_PASSWORD. Environment variables are better in scripts, because no file is left on disk.
Then install from TestPyPI in a fresh environment:
python -m venv /tmp/testpypi-check
/tmp/testpypi-check/bin/pip install \
--index-url https://test.pypi.org/simple/ \
--extra-index-url https://pypi.org/simple/ \
greeter
/tmp/testpypi-check/bin/greeter AdaThe --extra-index-url is needed because your dependencies are probably not on TestPyPI. See the warning below about what this setting risks.
Publish to PyPI
When TestPyPI looks right, upload the same files to PyPI:
python -m twine upload dist/*Do not rebuild between the two uploads. Uploading the identical files means you published what you tested.
When it succeeds, twine prints the URL of the release page. Check these things there:
- The README renders as the project description.
- The version, Python requirement, and license are correct.
- Both files are listed under "Download files".
- The classifiers appear in the sidebar.
Then confirm a real install from a clean environment:
python -m venv /tmp/pypi-check
/tmp/pypi-check/bin/pip install greeter==0.1.0
/tmp/pypi-check/bin/python -c "import greeter; print(greeter.__version__)"A new release can take a short moment to show up in pip's results. If pip cannot find it, wait a minute and retry with --no-cache-dir.
What happens during an upload
The diagram shows the sequence for one upload.
Each file is sent as a separate request. If the sdist uploads and the wheel fails, you end up with a partial release. You fix the cause and upload the missing file. You do not need to bump the version, as long as the missing file's name has not been used.
Common errors
| Message | Cause | Fix |
|---|---|---|
| `403 Invalid or non-existent authentication information` | Wrong username, bad token, or a TestPyPI token used on PyPI | Use `__token__` as the username and a token for the right index |
| `400 File already exists` | That filename was uploaded before | Bump the version and rebuild |
| `403 The user ... isn't allowed to upload to project` | The name belongs to someone else, or your token is scoped to another project | Pick another name or fix the token scope |
| `400 ... is not a valid version` | The version string is not PEP 440 | Correct the `version` field |
| `InvalidDistribution: Metadata is missing required fields` | Old `twine` or a malformed build | Upgrade `twine` and `build`, then rebuild |
| Description shows as plain text | README format not detected | Set `readme = "README.md"` in `pyproject.toml` and rerun `twine check` |
The File already exists error is the one people hit most. Deleting the release on PyPI does not free the filename. The only fix is a new version number.
Security habits
- Scope tokens to one project after the first upload.
- Keep tokens out of shell history. Use
~/.pypircor a password manager, not a token pasted in a command. - Use a separate token per machine or workflow so you can revoke one without breaking the others.
- Revoke a token at once if it appears in a log, a commit, or a screenshot.
Long-lived tokens still carry risk, even when scoped. A later chapter replaces them with trusted publishing, where the upload is authorized by a short-lived identity from your CI system.
Summary of the release steps
- Choose a new, unused PEP 440 version.
- Delete
dist/, then runpython -m build. - Run
python -m twine check dist/*. - Upload to TestPyPI and install from there.
- Upload the same files to PyPI.
- Install from PyPI in a clean environment and run it.
Exercise
You uploaded greeter 0.1.0 to PyPI and then noticed a typo in the README. You delete the release in the PyPI web interface, fix the typo, rebuild, and run twine upload dist/* again with the same version. What happens, and what should you do instead?
Show answer
The upload fails with 400 File already exists. Deleting a release does not free its filenames, so 0.1.0 can never be uploaded again. Change the version to 0.1.1 (or add a post-release such as 0.1.0.post1), delete dist/, rebuild, run twine check, and upload the new files.
Exercise
Why is it better to upload the exact files you tested on TestPyPI to PyPI, instead of running python -m build again between the two uploads?
Show answer
A rebuild can produce files that differ from the ones you tested, for example if the working tree, dependencies of the build backend, or timestamps changed. Uploading the same files guarantees that the release on PyPI is the one you verified.