Python Packaging Primer

from 0 to PyPI in 15 minutes

(hopefully...)

What we mean by "Packaging"?

The process of installing, upgrading or publishing Python source code

Glossary

Module
The basic unit of code reusability in Python.
(Import) Package
A Python module which can contain other modules or recursively, other packages.
(Distribution) Package
A versioned archive file that contains Python packages, modules, resource files. Used to distribute a Release. What users download from the internet and install.

https://python-packaging-user-guide.readthedocs.org/en/latest/glossary/

Setup

            $ mkdir athina
            $ cd athina
            $ python -m venv .venv
            $ source .venv/bin/activate
            $ pip install -U setuptools pip wheel twine
          

athens.py (our module)


def hi():
    return 'Hi Athens!'
          

setup.py


from setuptools import setup


setup(
    name='athina',
    version='0.1.0',
    description='A sample Python project',
    long_description='Long description of the package should be here.',
    url='https://projectsite.com',
    author='John Doe',
    author_email='john@example.com',
    license='MIT',
    platforms='any',
    py_modules=['athina']
)
          

Source Distribution (or "sdist")

A distribution format that provides metadata and the essential source files needed for installing by a tool like pip, or for generating a Built Distribution.

$ python setup.py sdist

Built Distribution (or "bdist")

A Distribution format containing files and metadata that only need to be moved to the correct location on the target system, to be installed

Wheel

A Built Distribution format

$ python setup.py bdist_wheel --universal

Python Package Index

https://pypi.python.org

or for testing

https://testpypi.python.org

.pypirc


[distutils]
index-servers=
    pypi
    testpypi

[pypi]
repository = https://pypi.python.org/pypi
username = alefteris

[testpypi]
repository = https://testpypi.python.org/pypi
username = thale
          

Register Package

$ twine register -r testpypi dist/athina-0.1.0.tar.gz

Upload

$ twine upload -r testpypi dist/*

Install

$ pip install -i https://testpypi.python.org/pypi athina

Resources

  • Python Packaging Authority (PyPA)
    https://www.pypa.io
  • Python Packaging User Guide (PyPUG)
    https://packaging.python.org
  • A sample Python project by Python Packaging Authority
    https://github.com/pypa/sampleproject
  • Python Cookiecutters
    https://github.com/audreyr/cookiecutter#python

The End

Here is a cat packaged