How to use PyPi to distribute Python packages

1 minute read

Related: Replace/augment setup.py with pyproject.toml


This procedure is for PyPi Warehouse and requires secure, powerful twine uploader.

PyPi upload

This assumes you already have the setup.py and setup.cfg structure below.

Prereqs:

  • setuptools >= 38.6.0
  • twine >= 1.11.0

one-time setup

  1. Sign up for PyPi account.
  2. Install Twine
    python -m pip install twine
    
  3. create ~/.pypirc with the content
    [pypi]
    username=pypiusername
    

Note that I did NOT save my password for security.

Upload

  1. In your Python package directory to upload
    python setup.py sdist bdist_wheel
       
    twine upload dist/*
    
  2. Now the package is live to the world on PyPi. Anyone can install it via
    python -m pip install myprogram
    

Minimal setup.py, setup.cfg

  1. assuming your package is named myprogram, have a directory structure like
    setup.cfg
    setup.py
    myprogram/
        __init__.py
    
  2. minimal setup.py for PyPi:
    from setuptools import setup; setup()
    

    NOTE: you must always have a setuptools import when using setup.py to build distribution, EVEN IF you don’t explicitly use it. Use # noqa: F401 to quiet linters.

  3. minimal setup.cfg for PyPi enabling Markdown README. Pick from the list of classifiers suitable for your project.

You MUST increment the version number for each release, or PyPi will prevent upload

Error workarounds

error: Upload failed (400): Binary wheel ‘*-cp36-cp36m-linux_x86_64.whl’ has an unsupported platform tag ‘linux_x86_64’.

This error happens because currently only manylinux1 wheels are accepted by PyPi. It is not trivial to first start building manylinux1 wheels, so consider workaround: don’t upload the wheel, just the source code and your users will compile it on their machine.

python setup.py sdist 
twine upload dist/*

Leave a Comment