Publishing a Python library to PyPI with Flit
Project setup
Create a project config file named pyproject.toml
,
as described in the Flit docs.
Put the library package (folder containing an __init__.py
)
inside a folder named src
in the project root.
This is to ensure that when the tests run,
they import your library from the venv site-packages,
rather than the source files in the project folder.
PyPI account setup
Create an account on both PyPI and TestPyPI.
For each account, generate an API key. It’s fine to make a single one with global scope: I think the per-project ones are mainly for use in CI.
These API keys can be stored in a user-readable PyPI config file.
It must be named ~/.pypirc
and looks like this:
[distutils]
index-servers =
pypi
testpypi
[pypi]
username = __token__
password = { API key for PyPI (no quotes) }
[testpypi]
repository = https://test.pypi.org/legacy/
username = __token__
password = { API key for Test PyPI (no quotes) }
Set the permissions on the file to o=rw
with: chmod 600 ~/.pypirc
.
Publication test run
Make sure that Flit is installed: flit --version
.
(It can be installed via the package manager; doesn’t need to be in a venv.)
Remember to set the relevant classifiers in your pyproject.toml
,
and to remove “Private :: Do Not Upload”, if you had previously included it.
Then build and upload the package to the Test PyPI server:
flit publish --use-vcs --repository testpypi
The --use-vcs
flag is currently optional,
but the default is going to change in an upcoming release.
It causes the tests, licence file, build scripts, and extra documentation
to get added to the tarball (but not to the wheel).
Check that it can be installed properly in a new venv:
python3 -m venv .test
source .test/bin/activate.fish
pip install --index-url https://test.pypi.org/simple/ --no-deps { package name }
python -m pydoc { package name }
python -ic "import { package name }"
deactivate
rm -r .test
If everything looks good, the package can be published to PyPI.
Publication, for real
Just repeat the flit
command, but with the default repository:
flit publish --use-vcs